Search code examples
javastringlistarraylistjava-stream

Convert List<List<String>> to a List<String>


I have a ArrayList<List<String>> which contains data. e.g:

[[1,2,3],[1,2,3],[1,2,3]]

I tried to convert it into a List<String> but it becomes

[1,2,3,1,2,3,1,2,3]

Code:

List<String> f = 
            ch.stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());
    System.out.println(f);

How can I convert it into the following output so could get a index by list.get(index)?

List<String> list = [1,2,3],[1,2,3],[1,2,3];

Solution

  • Are you after the following?

        List<List<String>> ch = List.of(List.of("1", "2", "3"), List.of("1", "2", "3"), List.of("1", "2", "3"));
        
        System.out.println(ch);
        
        List<String> f = ch.stream()
                .map(List::toString)
                .collect(Collectors.toList());
        
        System.out.println(f);
    

    In the output the two lists look the same:

    [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
    [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
    

    But we can see from the code that the former is a list of lists, the latter just a list of strings.

    Since Java 16 prefer just .toList() over .collect(Collectors.toList()).

    Link: Differences of Java 16's Stream.toList() and Stream.collect(Collectors.toList())?