I'm learning how to use Java streams and need some help understanding how to stream nested collections and collect the results back into a collection.
In the simple example below, I've created 2 ArrayLists and added them to an ArrayList. I want to be able to perform a simple function on each nested collection and then capture the results into a new collection. The last line of code doesn't even compile. Any explanations would be appreciated!
ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(1,2,3));
ArrayList<Integer> list2 = new ArrayList<Integer>(Arrays.asList(4,5,6));
ArrayList<ArrayList<Integer>> nested = new ArrayList<ArrayList<Integer>>();
nested.add(list1);
nested.add(list2);
ArrayList<ArrayList<Integer>> result = nested.stream()
.map(list -> list.add(100))
.collect(Collectors.toList());
The problem is that List#add
doesn't return a List
. Instead, you need to return the list after the mapping:
List<ArrayList<Integer>> result = nested.stream()
.map(list -> {
list.add(100);
return list;
})
.collect(Collectors.toList());
Or you may skip using map
and do it using forEach
, since ArrayList
is mutable:
nested.forEach(list -> list.add(100));
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