Created
May 29, 2018 10:50
-
-
Save eliezio/b7b250954fc4285b229b618943198e04 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public final class Utils { | |
public static List<Integer> flatIntegers(Collection col) { | |
if (col == null) { | |
throw new IllegalArgumentException("Collection cannot be null"); | |
} | |
List<Integer> result = new ArrayList<>(); | |
Deque<Iterator> queue = new ArrayDeque<>(); | |
queue.add(col.iterator()); | |
while (!queue.isEmpty()) { | |
Iterator it = queue.remove(); | |
while (it.hasNext()) { | |
Object element = it.next(); | |
if (element instanceof Collection) { | |
queue.add(it); | |
it = ((Collection) element).iterator(); | |
} else if (element instanceof Integer) { | |
result.add((Integer) element); | |
} else if (element == null) { | |
throw new IllegalArgumentException("Invalid null element found"); | |
} else { | |
throw new IllegalArgumentException( | |
"Element must be either a Collection or an integer, but it is a " + element.getClass().getName()); | |
} | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment