Advertisement
Guest User

Untitled

a guest
Jun 28th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. import java.util.Objects;
  5.  
  6. /*
  7. * This is a Utility class that provides the capability of flattening arbitrarily nested
  8. * arrays of integers.
  9. * The code operates by recursively processing nested arrays.
  10. * For ease of use, the nested arrays are represented as nested lists.
  11. */
  12.  
  13. public class Flattener {
  14.  
  15. /**
  16. * Recursively flattens a nested list of integers.
  17. * Only Integers and lists are accepted as part of the input.
  18. *
  19. *
  20. * @param input The nested list of integers to flatten
  21. * @return A flat list of integers
  22. * @exception IllegalArgumentException is thrown if the input tree contains anything else but integers or lists
  23. * @exception NullPointerException is thrown if the input is null, or contains nulls
  24. */
  25. public static List<Integer> flatten(List<?> input) {
  26. //Do not accept null input
  27. Objects.requireNonNull(input, "The input list must not be null");
  28. List<Integer> flat = new ArrayList<>();
  29.  
  30. //Process the list
  31. for (Object element : input) {
  32. if (element instanceof Integer) {
  33. //integers are directly added to the flat list
  34. flat.add((Integer)element);
  35. } else if (element instanceof List) {
  36. //lists are recursively flattened before adding all elements to the flat list
  37. flat.addAll(Flattener.flatten((List<?>)element));
  38. } else {
  39. //The element does not have one of the expected data types of integer or list
  40. // => signal an exception
  41. throw new IllegalArgumentException("Unsupported data type found: " + element.getClass().getName());
  42. }
  43. }
  44. return flat;
  45. }
  46.  
  47. public static void main(String[] args) {
  48. //Try the flattening function out on different inputs for test purposes
  49. List<List<Object>> inputs = Arrays.asList(
  50. Arrays.asList(),
  51. Arrays.asList(Arrays.asList(Arrays.asList())),
  52. Arrays.asList(Arrays.asList(1,2,Arrays.asList(3)),4),
  53. Arrays.asList(1,2, Arrays.asList(3,4), 5, Arrays.asList(Arrays.asList(6,7,8), Arrays.asList(9), Arrays.asList()))
  54. );
  55.  
  56. inputs.forEach(input -> System.out.println("flatten(" + input + ") = " + Flattener.flatten(input)));
  57.  
  58. // This is the actual output just for reference:
  59. // flatten([]) = []
  60. // flatten([[[]]]) = []
  61. // flatten([[1, 2, [3]], 4]) = [1, 2, 3, 4]
  62. // flatten([1, 2, [3, 4], 5, [[6, 7, 8], [9], []]]) = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  63.  
  64. }
  65.  
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement