Skip to content

Instantly share code, notes, and snippets.

@eliezio
Created May 29, 2018 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliezio/b7b250954fc4285b229b618943198e04 to your computer and use it in GitHub Desktop.
Save eliezio/b7b250954fc4285b229b618943198e04 to your computer and use it in GitHub Desktop.
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