Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert 2D list to 1D list with Streams?

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?

like image 275
ack Avatar asked May 29 '17 23:05

ack


People also ask

How do you convert a 1D list to a 2D list?

Using islice. The islice function can be used to slice a given list with certain number of elements as required by the 2D list. So here week looked through each element of the 2D list and use that value 2 slice the original list. We need itertools package to use the islice function.


3 Answers

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());
like image 129
Ousmane D. Avatar answered Sep 17 '22 23:09

Ousmane D.


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

like image 37
Amit Phaltankar Avatar answered Sep 20 '22 23:09

Amit Phaltankar


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]
like image 45
Elliott Frisch Avatar answered Sep 19 '22 23:09

Elliott Frisch