I got in touch with a new feature since java-9 called Collectors.flatMapping that takes place as a downstream of grouping or partitioning. Such as (example taken from here):
For just this particular case, I guess this would be a simpler version:
Map> map =
list.stream()
.collect(Collectors.toMap(
Collection::size,
x -> x.stream().filter(y -> y % 2 == 0).collect(Collectors.toList())
));
If there would be merging involved (two collections that would have the same size), I would add a merge
function that is pretty trivial:
Map> map =
list.stream()
.collect(Collectors.toMap(
Collection::size,
x -> x.stream().filter(y -> y % 2 == 0).collect(Collectors.toCollection(ArrayList::new)),
(left, right) -> {
left.addAll(right);
return left;
}
));
Otherwise, I agree with Michael in this comment, this is not that hard to back-port to java-8.