Learnitweb

Flatten a List of Lists

Approach 1: Using flatMap()

List<List<Integer>> lol = Arrays.asList(Arrays.asList(1,2), Arrays.asList(3,4));
List<Integer> flat = lol.stream().flatMap(List::stream).collect(Collectors.toList());
System.out.println(flat); // [1, 2, 3, 4]

Why it works:

  • flatMap() flattens nested streams into a single stream.

Approach 2: Flatten and Collect to Specific Set

Set<Integer> flatDistinct = lol.stream()
                               .flatMap(Collection::stream)
                               .collect(Collectors.toCollection(LinkedHashSet::new));
System.out.println(flatDistinct); // [1, 2, 3, 4]

Why it works:

  • Ensures distinct elements while preserving order.