Skip to content

Instantly share code, notes, and snippets.

@jayapradha
Last active March 10, 2016 04:07
Show Gist options
  • Save jayapradha/d328cd9c965e2aff972f to your computer and use it in GitHub Desktop.
Save jayapradha/d328cd9c965e2aff972f to your computer and use it in GitHub Desktop.
public class Flattener {
/**
* Flattens an array of arbitrarily nested arrays of integers into
* a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4]
*
* @param nestedNumbers - array ob objects (either plain integers or nested arrays of integers)
* @return - flat array of Integers
*/
public static List<Integer> flatten(Object[] nestedNumbers) {
if (nestedNumbers == null) return null;
List<Integer> flattenedNumbers = new ArrayList<>();
for (Object element : nestedNumbers) {
if (element instanceof Integer) {
flattenedNumbers.add((Integer)element);
} else {
flattenedNumbers.addAll(flatten((Object[]) element));
}
}
return flattenedNumbers;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment