JDK-8131310 : Stream API: add a mapping collector
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util.stream
  • Affected Version: 8u45
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_8
  • CPU: x86
  • Submitted: 2015-07-14
  • Updated: 2015-07-15
  • Resolved: 2015-07-15
Related Reports
Duplicate :  
Description
A DESCRIPTION OF THE REQUEST :
I'd like to have a convenience "mapping" collector, analog to the recently added "flatMapping" collector.

JUSTIFICATION :
JDK-8071600 added a "flatMapping" collector. However, in my experience the case of mapping is common enough to justify adding an extra convenience collector for this purpose. This makes the code more concise & allows to use method references for the mapping function.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
As an example: in Java 8 I wrote a custom collector to do a "groupingByAndMap" operation, i.e. transform Stream<T> into Map<K, List<U>> using a classifier T -> K and mapper T -> U

Adding the following convenience method in java.util.stream.Collectors:

public static <T, U, A, R> Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper, Collector<? super U, A, R> downstream) {
    return flatMapping(mapper.andThen(Stream::of), downstream);
}

would allow me to implement the "groupingByAndMap" operation as:

groupingBy(classifier, mapping(mapper, toList())

and also allows to use a method reference:

groupingBy(classifier, mapping(String::length, toList())

ACTUAL -
Currently (with Java 9 ea builds), implementing the "groupingByAndMap" operation is possible as:

groupingBy(classifier, flatMapping(mapper.andThen(Stream::of), toList())

However, this is not as readable. Moreoever, with this you cannot use a method reference. For example, you cannot write:

groupingBy(classifier, flatMapping(String::length.andThen(Stream::of), toList())



Comments
See Collectors.mapping: http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#mapping-java.util.function.Function-java.util.stream.Collector-
15-07-2015