Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. package code.flattener;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.List;
  6.  
  7. /**
  8. * Flattens an array of arbitrarily nested arrays of integers into a flat array of integers.
  9. * <p/>
  10. * @author conorgriffin
  11. */
  12. public class IntegerArrayFlattener {
  13.  
  14. /**
  15. * 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].
  16. *
  17. * @param inputArray an array of Integers or nested arrays of Integers
  18. * @return flattened array of Integers or null if input is null
  19. * @throws IllegalArgumentException
  20. */
  21. public static Integer[] flatten(Object[] inputArray) throws IllegalArgumentException {
  22.  
  23. if (inputArray == null) return null;
  24.  
  25. List<Integer> flatList = new ArrayList<Integer>();
  26.  
  27. for (Object element : inputArray) {
  28. if (element instanceof Integer) {
  29. flatList.add((Integer) element);
  30. } else if (element instanceof Object[]) {
  31. flatList.addAll(Arrays.asList(flatten((Object[]) element)));
  32. } else {
  33. throw new IllegalArgumentException("Input must be an array of Integers or nested arrays of Integers");
  34. }
  35. }
  36. return flatList.toArray(new Integer[flatList.size()]);
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement