Close

Java - How to convert a collection of any nested depth to a flat collection?

[Updated: Apr 29, 2017, Created: Apr 29, 2017]

Java 8 Streams Java 

This example shows how to convert a collection of unknown nested levels to a flat collection of a specified target type. it uses java.util.stream.Stream#flatMap

public class FlatCollectionExample {

  public static void main(String... args) {
      List<?> list = createExampleList();
      System.out.println("the input list: " + list);
      List<String> result = toFlatList(list, String.class);
      System.out.println("the flat list: " + result);
  }

  //this method can work with any nested level
  public static <T> List<T> toFlatList(Collection<?> collection, Class<T> targetType) {
      List<Object> result =
              collection.stream()
                        .flatMap(child -> {
                            if (child == null) {
                                return Stream.empty();
                            } else if (child instanceof Collection) {
                                return toFlatList((Collection<?>) child, targetType)
                                        .stream();
                            } else if (child.getClass().isAssignableFrom(targetType)) {
                                return Stream.of(child);
                            } else {
                                //ignore because it's not targetType T
                                return Stream.empty();
                            }
                        })
                        .collect(Collectors.toList());
      return (List<T>) result;
  }

  private static List<?> createExampleList() {
      return Arrays.asList(
              Arrays.asList(Arrays.asList(Arrays.asList("one"), "two"), Arrays.asList("five", "six")),
              Arrays.asList(Arrays.asList("three", Collections.singletonList("four")),
                      Arrays.asList("seven", "eight"), "nine", 10, null, Collections.singletonList(null))
      );
  }
}

Output

the input list: [[[[one], two], [five, six]], [[three, [four]], [seven, eight], nine, 10, null, [null]]]
the flat list: [one, two, five, six, three, four, seven, eight, nine]

See Also