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):
List<List<Integer>> list = Arrays.asList(
Arrays.asList(1, 2, 3, 4, 5, 6),
Arrays.asList(7, 8, 9, 10));
Map<Integer, List<Integer>> map =list.stream()
.collect(Collectors.groupingBy(
Collection::size,
Collectors.flatMapping(
l -> l.stream().filter(i -> i % 2 == 0),
Collectors.toList())));
{4=[8, 10], 6=[2, 4, 6]}
This is a fairly elegant way using just 3 collectors. I need to rewrite the collector in java-8 where is not yet supported. My attempt use 6 Collectors that is quite an extensive usage and I am not able to figure out a way using less of them:
Map<Integer, List<Integer>> map = list.stream()
.collect(Collectors.groupingBy(
Collection::size,
Collectors.collectingAndThen(
Collectors.mapping(
l -> l.stream().filter(i -> i % 2 == 0).collect(Collectors.toList()),
Collectors.toList()),
i -> i.stream().flatMap(j -> j.stream()).collect(Collectors.toList()))));
Is there a shorter better way using solely java-8?
Best Answer
I would just backport
flatMapping
. It only requires 2 methods and 1 class, with no other dependencies.Also, when it comes time to upgrade to Java 9, you can just deprecate your version and replace any usages of it with the proper version.
The following code is taken from the JDK. I didn't write it. I have tested it with your example and it returns the same result.
Sample usage: