7

I've tried this code (list is ArrayList<List<Integer>>):

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

but it doesn't do anything; the list is still a 2D list. How can I convert this 2D list to a 1D list?

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
ack
  • 1,181
  • 1
  • 17
  • 36

3 Answers3

7

Reason being that you're still receiving a list of lists is because when you apply Stream::of it's returning a new stream of the existing ones.

That is when you perform Stream::of it's like having {{{1,2}}, {{3,4}}, {{5,6}}} then when you perform flatMap it's like doing 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

rather you can use .flatMap(Collection::stream) to take a stream of streams such as:

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

and turn it into:

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

Therefore, you can change your current solution to:

List<Integer> result = list.stream().flatMap(Collection::stream)
                           .collect(Collectors.toList());
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
2

Simple solution is:

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);

Answer: [1, 2, 3, 4]

Hope this helps you

Amit Phaltankar
  • 3,341
  • 2
  • 20
  • 37
1

You can use x.stream() in your flatMap. Something like,

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);

Which outputs (like I think you wanted)

[1, 2, 3, 4, 5, 6]
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249