How can I flatten a List<List<List<String>>>

Viewed 117

I am trying to flatten a Big List:

List<List<List<String>>> input

Example of my list:

[[[a,b],[c,b]], [[x],[y]]]`

I want the result to be as follows:

[[a,b,c],[x,y]]

For the duplicates, I will try to use LinkedHashSet, but I can not flatten the list.

3 Answers
List<List<String>> result = 
    list.stream()
        .map(x -> x.stream()
                   .flatMap(List::stream)
                   .distinct()
                   .collect(Collectors.toList()))
        .collect(Collectors.toList());

Not much different, and much simple as in:

List<List<List<String>>> input = List.of(
        List.of(List.of("a", "b"), List.of("c", "b")),
        List.of(List.of("x"), List.of("y"))
);

List<LinkedHashSet<String>> output = input.stream()
        .map(l -> l.stream()
                .flatMap(Collection::stream)
                .collect(Collectors.toCollection(LinkedHashSet::new)))
        .collect(Collectors.toList());

You can do like this:

List<Set<String>> result = new ArrayList<>();
lists.forEach(list -> result.add(list.stream()
            .flatMap(List::stream)
            .collect(Collectors.toSet())));

or

lists.stream()
      .collect(
           () -> new ArrayList<Set<String>>(),      
           (sets, l) -> sets.add(l.stream()
                         .flatMap(List::stream)
                         .collect(Collectors.toSet())),
            List::addAll);
Related