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

Add a flat-mapping collector

    XMLWordPrintable

Details

    Backports

      Description

        When collecting elements of a stream and producing a summary result (such as a
        multi-map with `groupingBy`) it can tricky to map an element downstream to zero
        or more elements after which those mapped elements are further operated on.

        A `flatMapping` collector that maps an element to a Stream of zero or more
        mapped elements can be added to `Collectors`:

            public static <T, U, A, R>
            Collector<T, ?, R> flatMapping(Function<? super T, ? extends Stream<? extends U>> mapper,
                                           Collector<? super U, A, R> downstream) {
                BiConsumer<A, ? super U> downstreamAccumulator = downstream.accumulator();
                return Collector.of(downstream.supplier(),
                                    (r, t) -> mapper.apply(t).sequential().forEach(u -> downstreamAccumulator.accept(r, u)),
                                    downstream.combiner(),
                                    downstream.finisher(),
                                    downstream.characteristics().stream().toArray(Collector.Characteristics[]::new));
            }

        Attachments

          Issue Links

            Activity

              People

                psandoz Paul Sandoz
                psandoz Paul Sandoz
                Votes:
                0 Vote for this issue
                Watchers:
                3 Start watching this issue

                Dates

                  Created:
                  Updated:
                  Resolved: