Skip to content

Instantly share code, notes, and snippets.

@madhur
Created August 15, 2017 14:16
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 madhur/33c12de6d6612a7170294006c631607c to your computer and use it in GitHub Desktop.
Save madhur/33c12de6d6612a7170294006c631607c to your computer and use it in GitHub Desktop.
test.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by madhur on 15 Aug.
*/
public class IntegerArrayFlattener {
/**
* Flatten 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 inputArray an array of Integers or nested arrays of Integers
* @return flattened array of Integers or null if input is null
* @throws IllegalArgumentException
*/
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