How to convert a 2D list to a 1D list using Streams?

I tried this code ( listis ArrayList<List<Integer>>):

list.stream().flatMap(Stream::of).collect(Collectors.toList());

but he does nothing; the list is still a 2D list. How to convert this 2D list to 1D list?

+6
source share
3 answers

The reason that you still get the list of lists is that when you apply Stream::of, it returns a new stream of the existing one.

That is, when you perform Stream::of, he likes to have {{{1,2}}, {{3,4}}, {{5,6}}}, then when you perform flatMaphe likes to do this:

{{{1,2}}, {{3,4}}, {{5,6}}} -> flatMap -> {{1,2}, {3,4}, {5,6}}
// result after flatMap removes the stream of streams of streams to stream of streams

.flatMap(Collection::stream) , :

{{1,2}, {3,4}, {5,6}}

:

{1,2,3,4,5,6}

:

List<Integer> result = list.stream().flatMap(Collection::stream)
                           .collect(Collectors.toList());
+6

:

List<List<Integer>> listOfLists = Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4));
List<Integer> faltList = listOfLists.
        stream().flatMap(s -> s.stream()).collect(Collectors.toList());
System.out.println(faltList);

: [1, 2, 3, 4]

,

+2

You can use x.stream()in your own flatMap. Sort of,

ArrayList<List<Integer>> list = new ArrayList<>();
list.add(Arrays.asList((Integer) 1, 2, 3));
list.add(Arrays.asList((Integer) 4, 5, 6));
List<Integer> merged = list.stream().flatMap(x -> x.stream())
        .collect(Collectors.toList());
System.out.println(merged);

What are the outputs (as I think you wanted)

[1, 2, 3, 4, 5, 6]
+1
source

All Articles