Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8131310

Stream API: add a mapping collector

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Duplicate
    • Icon: P4 P4
    • None
    • 8u45
    • core-libs

      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())


            psandoz Paul Sandoz
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: