Skip to content

Instantly share code, notes, and snippets.

@shahamit
Created December 9, 2016 10:52
Show Gist options
  • Save shahamit/f993e08e0601ff024f7a64ad39139470 to your computer and use it in GitHub Desktop.
Save shahamit/f993e08e0601ff024f7a64ad39139470 to your computer and use it in GitHub Desktop.
Flatten arbitrarily nested arrays
public static Integer[] flatten(Object[] inputArray) throws IllegalArgumentException {
if (inputArray == null) return null;
List<Integer> flatList = new ArrayList<Integer>();
for (Object element : inputArray) {
if (element instanceof Integer) {
flatList.add((Integer) element);
} else if (element instanceof Object[]) {
flatList.addAll(Arrays.asList(flatten((Object[]) element)));
} else {
throw new IllegalArgumentException("Input must be an array of Integers or nested arrays of Integers");
}
}
return flatList.toArray(new Integer[flatList.size()]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment