Collapse List<List<String>> into List<String> using a lambda?
Asked Answered
A

4

7

Say I have a list of Lists..

List<List<String>> lists = new ArrayList<>();

Is there a clever lambda way to collapse this into a List of all the contents ?

Anemoscope answered 19/9, 2014 at 19:57 Comment(0)
H
16

That's what flatMap is for :

List<String> list = inputList.stream() // create a Stream<List<String>>
                             .flatMap(l -> l.stream()) // create a Stream<String>
                                                       // of all the Strings in
                                                       // all the internal lists
                             .collect(Collectors.toList());
Hachure answered 19/9, 2014 at 20:1 Comment(2)
Looks like you answer all the flatMap questions. :-) Note the lambda could also be replaced with List::stream.Kurtzig
This answers is very usefullyDispirited
U
2

You can do

List<String> result = lists.stream()
    .flatMap(l -> l.stream())
    .collect(Collectors.toList());
Unwish answered 19/9, 2014 at 20:0 Comment(2)
Don't think this will work--the argument of flatMap has to be a function that turns a List<String> into a Stream<String>. See the javadoc.Mesopotamia
@Mesopotamia : Taking another look to the Function.identity() doc, you are right. Thanks !Unwish
H
0
/*
        Let's say you have list of list of person names as below
        [[John, Wick], [Patric, Peter], [Nick, Bill]]
    */
    List<List<String>> personsNames =
            List.of(List.of("John", "Wick"), List.of("Patric", "Peter"), List.of("Nick", "Bill"));

    List<String> finalList = personsNames
            .stream()
            .flatMap(name -> name.stream()).collect(toList());
    
    /*
    * Final result will be like - [John, Wick, Patric, Peter, Nick, Bill]
    */
Hartung answered 5/8, 2023 at 15:30 Comment(0)
F
-1
List<String> result = lists.stream().flatMap(Collection::stream)
.collect(Collectors.toList());
Feign answered 3/5, 2023 at 6:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.