I have a method that receives a collector. The collector should combine incoming lists:
reducing(Lists.newArrayList(), (container, list) -> {
container.addAll(list);
return container;
})
This seems like a very common scenario to me, and I believe Java's own collector should have something to cover this use case, but I cannot remember what. Besides, I want it to return ImmutableList
.
CodePudding user response:
To obtain a "flattened" list of elements from a nested collection firstly you need to apply flatMapping()
and then toUnmodifiableList()
as a downstream collector (as already mentioned by racraman and hfontanez in their comments, since they pointed that earlier the credits for this answer should belong to them, I'll leave it for informational purposes).
List<List<Integer>> nestedList = List.of(
List.of(1, 2),
List.of(3, 4)
);
nestedList.stream()
.collect(Collectors.flatMapping(List::stream,
Collectors.toUnmodifiableList()))
.forEach(System.out::println);
output
1
2
3
4
CodePudding user response:
We can also do flatMap() operation and toList() collector, to collect multiple incoming lists to one resultant list.
List<String> joinedList = Stream.of(
asList("1", "2"),
asList("3", "4")).flatMap(list -> list.stream()
)
.collect(toList());
System.out.println("Printing the list named as joinedList: " joinedList);
Output will be:
Printing the list named joinedList: [1, 2, 3, 4]