Skip to main content

How do I flatten a list of lists

In this Q&A, we'll go over how to use Java Stream APIs to flatten a list.

Stream provides a flatMap method that flattens nested List into a flat List.

List<List<String>> ll = Arrays.asList( Arrays.asList("1a", "2a", "3a"), Arrays.asList("4a", "5a",) );
ll.stream().flatMap(Collection::stream).forEach(System.out::println);

Stream also proivdes methods to create a flattened IntStream, LongStream or DoubleStream.
List<List<String>> ll = Arrays.asList( Arrays.asList("1a", "2a", "3a"), Arrays.asList("4a", "5a", "6a") );
ll.stream().flatMapToInt(x ->x.stream().mapToInt(Objects::hashCode)).forEach(System.out::println);


In addition to the Stream implementations, Optional class also provides a flatMap to flatten nested Optional objects.  See code below:
Optional<Optional<String>> o2 = Optional.of("HW").map(l -> Optional.of("hw"));
// flatten the Optional objects
Optional<String> o3 = Optional.of("HW").flatMap(l -> Optional.of("hw"));

Comments