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?
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.
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());
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With