1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package java.util.stream;
  26 
  27 import java.util.AbstractMap;
  28 import java.util.AbstractSet;
  29 import java.util.ArrayList;
  30 import java.util.Arrays;
  31 import java.util.Collection;
  32 import java.util.Collections;
  33 import java.util.Comparator;
  34 import java.util.DoubleSummaryStatistics;
  35 import java.util.EnumSet;
  36 import java.util.HashMap;
  37 import java.util.HashSet;
  38 import java.util.IntSummaryStatistics;
  39 import java.util.Iterator;
  40 import java.util.List;
  41 import java.util.LongSummaryStatistics;
  42 import java.util.Map;
  43 import java.util.Objects;
  44 import java.util.Optional;
  45 import java.util.Set;
  46 import java.util.StringJoiner;
  47 import java.util.concurrent.ConcurrentHashMap;
  48 import java.util.concurrent.ConcurrentMap;
  49 import java.util.function.BiConsumer;
  50 import java.util.function.BiFunction;
  51 import java.util.function.BinaryOperator;
  52 import java.util.function.Consumer;
  53 import java.util.function.Function;
  54 import java.util.function.Predicate;
  55 import java.util.function.Supplier;
  56 import java.util.function.ToDoubleFunction;
  57 import java.util.function.ToIntFunction;
  58 import java.util.function.ToLongFunction;
  59 
  60 /**
  61  * Implementations of {@link Collector} that implement various useful reduction
  62  * operations, such as accumulating elements into collections, summarizing
  63  * elements according to various criteria, etc.
  64  *
  65  * <p>The following are examples of using the predefined collectors to perform
  66  * common mutable reduction tasks:
  67  *
  68  * <pre>{@code
  69  *     // Accumulate names into a List
  70  *     List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());
  71  *
  72  *     // Accumulate names into a TreeSet
  73  *     Set<String> set = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new));
  74  *
  75  *     // Convert elements to strings and concatenate them, separated by commas
  76  *     String joined = things.stream()
  77  *                           .map(Object::toString)
  78  *                           .collect(Collectors.joining(", "));
  79  *
  80  *     // Compute sum of salaries of employee
  81  *     int total = employees.stream()
  82  *                          .collect(Collectors.summingInt(Employee::getSalary)));
  83  *
  84  *     // Group employees by department
  85  *     Map<Department, List<Employee>> byDept
  86  *         = employees.stream()
  87  *                    .collect(Collectors.groupingBy(Employee::getDepartment));
  88  *
  89  *     // Compute sum of salaries by department
  90  *     Map<Department, Integer> totalByDept
  91  *         = employees.stream()
  92  *                    .collect(Collectors.groupingBy(Employee::getDepartment,
  93  *                                                   Collectors.summingInt(Employee::getSalary)));
  94  *
  95  *     // Partition students into passing and failing
  96  *     Map<Boolean, List<Student>> passingFailing =
  97  *         students.stream()
  98  *                 .collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));
  99  *
 100  * }</pre>
 101  *
 102  * @since 1.8
 103  */
 104 public final class Collectors {
 105 
 106     static final Set<Collector.Characteristics> CH_CONCURRENT_ID
 107             = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.CONCURRENT,
 108                                                      Collector.Characteristics.UNORDERED,
 109                                                      Collector.Characteristics.IDENTITY_FINISH));
 110     static final Set<Collector.Characteristics> CH_CONCURRENT_NOID
 111             = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.CONCURRENT,
 112                                                      Collector.Characteristics.UNORDERED));
 113     static final Set<Collector.Characteristics> CH_ID
 114             = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH));
 115     static final Set<Collector.Characteristics> CH_UNORDERED_ID
 116             = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.UNORDERED,
 117                                                      Collector.Characteristics.IDENTITY_FINISH));
 118     static final Set<Collector.Characteristics> CH_NOID = Collections.emptySet();
 119 
 120     private Collectors() { }
 121 
 122     /**
 123      * Construct an {@code IllegalStateException} with appropriate message.
 124      *
 125      * @param k the duplicate key
 126      * @param u 1st value to be accumulated/merged
 127      * @param v 2nd value to be accumulated/merged
 128      */
 129     private static IllegalStateException duplicateKeyException(
 130             Object k, Object u, Object v) {
 131         return new IllegalStateException(String.format(
 132             "Duplicate key %s (attempted merging values %s and %s)",
 133             k, u, v));
 134     }
 135 
 136     /**
 137      * {@code BinaryOperator<Map>} that merges the contents of its right
 138      * argument into its left argument, throwing {@code IllegalStateException}
 139      * if duplicate keys are encountered.
 140      *
 141      * @param <K> type of the map keys
 142      * @param <V> type of the map values
 143      * @param <M> type of the map
 144      * @return a merge function for two maps
 145      */
 146     private static <K, V, M extends Map<K,V>>
 147     BinaryOperator<M> uniqKeysMapMerger() {
 148         return (m1, m2) -> {
 149             for (Map.Entry<K,V> e : m2.entrySet()) {
 150                 K k = e.getKey();
 151                 V v = Objects.requireNonNull(e.getValue());
 152                 V u = m1.putIfAbsent(k, v);
 153                 if (u != null) throw duplicateKeyException(k, u, v);
 154             }
 155             return m1;
 156         };
 157     }
 158 
 159     /**
 160      * {@code BiConsumer<Map, T>} that accumulates (key, value) pairs
 161      * extracted from elements into the map, throwing {@code IllegalStateException}
 162      * if duplicate keys are encountered.
 163      *
 164      * @param keyMapper a function that maps an element into a key
 165      * @param valueMapper a function that maps an element into a value
 166      * @param <T> type of elements
 167      * @param <K> type of map keys
 168      * @param <V> type of map values
 169      * @return an accumulating consumer
 170      */
 171     private static <T, K, V>
 172     BiConsumer<Map<K, V>, T> uniqKeysMapAccumulator(Function<? super T, ? extends K> keyMapper,
 173                                                     Function<? super T, ? extends V> valueMapper) {
 174         return (map, element) -> {
 175             K k = keyMapper.apply(element);
 176             V v = Objects.requireNonNull(valueMapper.apply(element));
 177             V u = map.putIfAbsent(k, v);
 178             if (u != null) throw duplicateKeyException(k, u, v);
 179         };
 180     }
 181 
 182     @SuppressWarnings("unchecked")
 183     private static <I, R> Function<I, R> castingIdentity() {
 184         return i -> (R) i;
 185     }
 186 
 187     /**
 188      * Simple implementation class for {@code Collector}.
 189      *
 190      * @param <T> the type of elements to be collected
 191      * @param <R> the type of the result
 192      */
 193     static class CollectorImpl<T, A, R> implements Collector<T, A, R> {
 194         private final Supplier<A> supplier;
 195         private final BiConsumer<A, T> accumulator;
 196         private final BinaryOperator<A> combiner;
 197         private final Function<A, R> finisher;
 198         private final Set<Characteristics> characteristics;
 199 
 200         CollectorImpl(Supplier<A> supplier,
 201                       BiConsumer<A, T> accumulator,
 202                       BinaryOperator<A> combiner,
 203                       Function<A,R> finisher,
 204                       Set<Characteristics> characteristics) {
 205             this.supplier = supplier;
 206             this.accumulator = accumulator;
 207             this.combiner = combiner;
 208             this.finisher = finisher;
 209             this.characteristics = characteristics;
 210         }
 211 
 212         CollectorImpl(Supplier<A> supplier,
 213                       BiConsumer<A, T> accumulator,
 214                       BinaryOperator<A> combiner,
 215                       Set<Characteristics> characteristics) {
 216             this(supplier, accumulator, combiner, castingIdentity(), characteristics);
 217         }
 218 
 219         @Override
 220         public BiConsumer<A, T> accumulator() {
 221             return accumulator;
 222         }
 223 
 224         @Override
 225         public Supplier<A> supplier() {
 226             return supplier;
 227         }
 228 
 229         @Override
 230         public BinaryOperator<A> combiner() {
 231             return combiner;
 232         }
 233 
 234         @Override
 235         public Function<A, R> finisher() {
 236             return finisher;
 237         }
 238 
 239         @Override
 240         public Set<Characteristics> characteristics() {
 241             return characteristics;
 242         }
 243     }
 244 
 245     /**
 246      * Returns a {@code Collector} that accumulates the input elements into a
 247      * new {@code Collection}, in encounter order.  The {@code Collection} is
 248      * created by the provided factory.
 249      *
 250      * @param <T> the type of the input elements
 251      * @param <C> the type of the resulting {@code Collection}
 252      * @param collectionFactory a {@code Supplier} which returns a new, empty
 253      * {@code Collection} of the appropriate type
 254      * @return a {@code Collector} which collects all the input elements into a
 255      * {@code Collection}, in encounter order
 256      */
 257     public static <T, C extends Collection<T>>
 258     Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
 259         return new CollectorImpl<>(collectionFactory, Collection<T>::add,
 260                                    (r1, r2) -> { r1.addAll(r2); return r1; },
 261                                    CH_ID);
 262     }
 263 
 264     /**
 265      * Returns a {@code Collector} that accumulates the input elements into a
 266      * new {@code List}. There are no guarantees on the type, mutability,
 267      * serializability, or thread-safety of the {@code List} returned; if more
 268      * control over the returned {@code List} is required, use {@link #toCollection(Supplier)}.
 269      *
 270      * @param <T> the type of the input elements
 271      * @return a {@code Collector} which collects all the input elements into a
 272      * {@code List}, in encounter order
 273      */
 274     public static <T>
 275     Collector<T, ?, List<T>> toList() {
 276         return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add,
 277                                    (left, right) -> { left.addAll(right); return left; },
 278                                    CH_ID);
 279     }
 280 
 281     /**
 282      * Returns a {@code Collector} that accumulates the input elements into a
 283      * new {@code Set}. There are no guarantees on the type, mutability,
 284      * serializability, or thread-safety of the {@code Set} returned; if more
 285      * control over the returned {@code Set} is required, use
 286      * {@link #toCollection(Supplier)}.
 287      *
 288      * <p>This is an {@link Collector.Characteristics#UNORDERED unordered}
 289      * Collector.
 290      *
 291      * @param <T> the type of the input elements
 292      * @return a {@code Collector} which collects all the input elements into a
 293      * {@code Set}
 294      */
 295     public static <T>
 296     Collector<T, ?, Set<T>> toSet() {
 297         return new CollectorImpl<>((Supplier<Set<T>>) HashSet::new, Set::add,
 298                                    (left, right) -> { left.addAll(right); return left; },
 299                                    CH_UNORDERED_ID);
 300     }
 301 
 302     /**
 303      * Returns a {@code Collector} that concatenates the input elements into a
 304      * {@code String}, in encounter order.
 305      *
 306      * @return a {@code Collector} that concatenates the input elements into a
 307      * {@code String}, in encounter order
 308      */
 309     public static Collector<CharSequence, ?, String> joining() {
 310         return new CollectorImpl<CharSequence, StringBuilder, String>(
 311                 StringBuilder::new, StringBuilder::append,
 312                 (r1, r2) -> { r1.append(r2); return r1; },
 313                 StringBuilder::toString, CH_NOID);
 314     }
 315 
 316     /**
 317      * Returns a {@code Collector} that concatenates the input elements,
 318      * separated by the specified delimiter, in encounter order.
 319      *
 320      * @param delimiter the delimiter to be used between each element
 321      * @return A {@code Collector} which concatenates CharSequence elements,
 322      * separated by the specified delimiter, in encounter order
 323      */
 324     public static Collector<CharSequence, ?, String> joining(CharSequence delimiter) {
 325         return joining(delimiter, "", "");
 326     }
 327 
 328     /**
 329      * Returns a {@code Collector} that concatenates the input elements,
 330      * separated by the specified delimiter, with the specified prefix and
 331      * suffix, in encounter order.
 332      *
 333      * @param delimiter the delimiter to be used between each element
 334      * @param  prefix the sequence of characters to be used at the beginning
 335      *                of the joined result
 336      * @param  suffix the sequence of characters to be used at the end
 337      *                of the joined result
 338      * @return A {@code Collector} which concatenates CharSequence elements,
 339      * separated by the specified delimiter, in encounter order
 340      */
 341     public static Collector<CharSequence, ?, String> joining(CharSequence delimiter,
 342                                                              CharSequence prefix,
 343                                                              CharSequence suffix) {
 344         return new CollectorImpl<>(
 345                 () -> new StringJoiner(delimiter, prefix, suffix),
 346                 StringJoiner::add, StringJoiner::merge,
 347                 StringJoiner::toString, CH_NOID);
 348     }
 349 
 350     /**
 351      * {@code BinaryOperator<Map>} that merges the contents of its right
 352      * argument into its left argument, using the provided merge function to
 353      * handle duplicate keys.
 354      *
 355      * @param <K> type of the map keys
 356      * @param <V> type of the map values
 357      * @param <M> type of the map
 358      * @param mergeFunction A merge function suitable for
 359      * {@link Map#merge(Object, Object, BiFunction) Map.merge()}
 360      * @return a merge function for two maps
 361      */
 362     private static <K, V, M extends Map<K,V>>
 363     BinaryOperator<M> mapMerger(BinaryOperator<V> mergeFunction) {
 364         return (m1, m2) -> {
 365             for (Map.Entry<K,V> e : m2.entrySet())
 366                 m1.merge(e.getKey(), e.getValue(), mergeFunction);
 367             return m1;
 368         };
 369     }
 370 
 371     /**
 372      * Adapts a {@code Collector} accepting elements of type {@code U} to one
 373      * accepting elements of type {@code T} by applying a mapping function to
 374      * each input element before accumulation.
 375      *
 376      * @apiNote
 377      * The {@code mapping()} collectors are most useful when used in a
 378      * multi-level reduction, such as downstream of a {@code groupingBy} or
 379      * {@code partitioningBy}.  For example, given a stream of
 380      * {@code Person}, to accumulate the set of last names in each city:
 381      * <pre>{@code
 382      *     Map<City, Set<String>> lastNamesByCity
 383      *         = people.stream().collect(groupingBy(Person::getCity,
 384      *                                              mapping(Person::getLastName, toSet())));
 385      * }</pre>
 386      *
 387      * @param <T> the type of the input elements
 388      * @param <U> type of elements accepted by downstream collector
 389      * @param <A> intermediate accumulation type of the downstream collector
 390      * @param <R> result type of collector
 391      * @param mapper a function to be applied to the input elements
 392      * @param downstream a collector which will accept mapped values
 393      * @return a collector which applies the mapping function to the input
 394      * elements and provides the mapped results to the downstream collector
 395      */
 396     public static <T, U, A, R>
 397     Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper,
 398                                Collector<? super U, A, R> downstream) {
 399         BiConsumer<A, ? super U> downstreamAccumulator = downstream.accumulator();
 400         return new CollectorImpl<>(downstream.supplier(),
 401                                    (r, t) -> downstreamAccumulator.accept(r, mapper.apply(t)),
 402                                    downstream.combiner(), downstream.finisher(),
 403                                    downstream.characteristics());
 404     }
 405 
 406     /**
 407      * Adapts a {@code Collector} to perform an additional finishing
 408      * transformation.  For example, one could adapt the {@link #toList()}
 409      * collector to always produce an immutable list with:
 410      * <pre>{@code
 411      *     List<String> people
 412      *         = people.stream().collect(collectingAndThen(toList(), Collections::unmodifiableList));
 413      * }</pre>
 414      *
 415      * @param <T> the type of the input elements
 416      * @param <A> intermediate accumulation type of the downstream collector
 417      * @param <R> result type of the downstream collector
 418      * @param <RR> result type of the resulting collector
 419      * @param downstream a collector
 420      * @param finisher a function to be applied to the final result of the downstream collector
 421      * @return a collector which performs the action of the downstream collector,
 422      * followed by an additional finishing step
 423      */
 424     public static<T,A,R,RR> Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream,
 425                                                                 Function<R,RR> finisher) {
 426         Set<Collector.Characteristics> characteristics = downstream.characteristics();
 427         if (characteristics.contains(Collector.Characteristics.IDENTITY_FINISH)) {
 428             if (characteristics.size() == 1)
 429                 characteristics = Collectors.CH_NOID;
 430             else {
 431                 characteristics = EnumSet.copyOf(characteristics);
 432                 characteristics.remove(Collector.Characteristics.IDENTITY_FINISH);
 433                 characteristics = Collections.unmodifiableSet(characteristics);
 434             }
 435         }
 436         return new CollectorImpl<>(downstream.supplier(),
 437                                    downstream.accumulator(),
 438                                    downstream.combiner(),
 439                                    downstream.finisher().andThen(finisher),
 440                                    characteristics);
 441     }
 442 
 443     /**
 444      * Returns a {@code Collector} accepting elements of type {@code T} that
 445      * counts the number of input elements.  If no elements are present, the
 446      * result is 0.
 447      *
 448      * @implSpec
 449      * This produces a result equivalent to:
 450      * <pre>{@code
 451      *     reducing(0L, e -> 1L, Long::sum)
 452      * }</pre>
 453      *
 454      * @param <T> the type of the input elements
 455      * @return a {@code Collector} that counts the input elements
 456      */
 457     public static <T> Collector<T, ?, Long>
 458     counting() {
 459         return reducing(0L, e -> 1L, Long::sum);
 460     }
 461 
 462     /**
 463      * Returns a {@code Collector} that produces the minimal element according
 464      * to a given {@code Comparator}, described as an {@code Optional<T>}.
 465      *
 466      * @implSpec
 467      * This produces a result equivalent to:
 468      * <pre>{@code
 469      *     reducing(BinaryOperator.minBy(comparator))
 470      * }</pre>
 471      *
 472      * @param <T> the type of the input elements
 473      * @param comparator a {@code Comparator} for comparing elements
 474      * @return a {@code Collector} that produces the minimal value
 475      */
 476     public static <T> Collector<T, ?, Optional<T>>
 477     minBy(Comparator<? super T> comparator) {
 478         return reducing(BinaryOperator.minBy(comparator));
 479     }
 480 
 481     /**
 482      * Returns a {@code Collector} that produces the maximal element according
 483      * to a given {@code Comparator}, described as an {@code Optional<T>}.
 484      *
 485      * @implSpec
 486      * This produces a result equivalent to:
 487      * <pre>{@code
 488      *     reducing(BinaryOperator.maxBy(comparator))
 489      * }</pre>
 490      *
 491      * @param <T> the type of the input elements
 492      * @param comparator a {@code Comparator} for comparing elements
 493      * @return a {@code Collector} that produces the maximal value
 494      */
 495     public static <T> Collector<T, ?, Optional<T>>
 496     maxBy(Comparator<? super T> comparator) {
 497         return reducing(BinaryOperator.maxBy(comparator));
 498     }
 499 
 500     /**
 501      * Returns a {@code Collector} that produces the sum of a integer-valued
 502      * function applied to the input elements.  If no elements are present,
 503      * the result is 0.
 504      *
 505      * @param <T> the type of the input elements
 506      * @param mapper a function extracting the property to be summed
 507      * @return a {@code Collector} that produces the sum of a derived property
 508      */
 509     public static <T> Collector<T, ?, Integer>
 510     summingInt(ToIntFunction<? super T> mapper) {
 511         return new CollectorImpl<>(
 512                 () -> new int[1],
 513                 (a, t) -> { a[0] += mapper.applyAsInt(t); },
 514                 (a, b) -> { a[0] += b[0]; return a; },
 515                 a -> a[0], CH_NOID);
 516     }
 517 
 518     /**
 519      * Returns a {@code Collector} that produces the sum of a long-valued
 520      * function applied to the input elements.  If no elements are present,
 521      * the result is 0.
 522      *
 523      * @param <T> the type of the input elements
 524      * @param mapper a function extracting the property to be summed
 525      * @return a {@code Collector} that produces the sum of a derived property
 526      */
 527     public static <T> Collector<T, ?, Long>
 528     summingLong(ToLongFunction<? super T> mapper) {
 529         return new CollectorImpl<>(
 530                 () -> new long[1],
 531                 (a, t) -> { a[0] += mapper.applyAsLong(t); },
 532                 (a, b) -> { a[0] += b[0]; return a; },
 533                 a -> a[0], CH_NOID);
 534     }
 535 
 536     /**
 537      * Returns a {@code Collector} that produces the sum of a double-valued
 538      * function applied to the input elements.  If no elements are present,
 539      * the result is 0.
 540      *
 541      * <p>The sum returned can vary depending upon the order in which
 542      * values are recorded, due to accumulated rounding error in
 543      * addition of values of differing magnitudes. Values sorted by increasing
 544      * absolute magnitude tend to yield more accurate results.  If any recorded
 545      * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 546      * sum will be {@code NaN}.
 547      *
 548      * @param <T> the type of the input elements
 549      * @param mapper a function extracting the property to be summed
 550      * @return a {@code Collector} that produces the sum of a derived property
 551      */
 552     public static <T> Collector<T, ?, Double>
 553     summingDouble(ToDoubleFunction<? super T> mapper) {
 554         /*
 555          * In the arrays allocated for the collect operation, index 0
 556          * holds the high-order bits of the running sum, index 1 holds
 557          * the low-order bits of the sum computed via compensated
 558          * summation, and index 2 holds the simple sum used to compute
 559          * the proper result if the stream contains infinite values of
 560          * the same sign.
 561          */
 562         return new CollectorImpl<>(
 563                 () -> new double[3],
 564                 (a, t) -> { sumWithCompensation(a, mapper.applyAsDouble(t));
 565                             a[2] += mapper.applyAsDouble(t);},
 566                 (a, b) -> { sumWithCompensation(a, b[0]);
 567                             a[2] += b[2];
 568                             return sumWithCompensation(a, b[1]); },
 569                 a -> computeFinalSum(a),
 570                 CH_NOID);
 571     }
 572 
 573     /**
 574      * Incorporate a new double value using Kahan summation /
 575      * compensation summation.
 576      *
 577      * High-order bits of the sum are in intermediateSum[0], low-order
 578      * bits of the sum are in intermediateSum[1], any additional
 579      * elements are application-specific.
 580      *
 581      * @param intermediateSum the high-order and low-order words of the intermediate sum
 582      * @param value the name value to be included in the running sum
 583      */
 584     static double[] sumWithCompensation(double[] intermediateSum, double value) {
 585         double tmp = value - intermediateSum[1];
 586         double sum = intermediateSum[0];
 587         double velvel = sum + tmp; // Little wolf of rounding error
 588         intermediateSum[1] = (velvel - sum) - tmp;
 589         intermediateSum[0] = velvel;
 590         return intermediateSum;
 591     }
 592 
 593     /**
 594      * If the compensated sum is spuriously NaN from accumulating one
 595      * or more same-signed infinite values, return the
 596      * correctly-signed infinity stored in the simple sum.
 597      */
 598     static double computeFinalSum(double[] summands) {
 599         // Better error bounds to add both terms as the final sum
 600         double tmp = summands[0] + summands[1];
 601         double simpleSum = summands[summands.length - 1];
 602         if (Double.isNaN(tmp) && Double.isInfinite(simpleSum))
 603             return simpleSum;
 604         else
 605             return tmp;
 606     }
 607 
 608     /**
 609      * Returns a {@code Collector} that produces the arithmetic mean of an integer-valued
 610      * function applied to the input elements.  If no elements are present,
 611      * the result is 0.
 612      *
 613      * @param <T> the type of the input elements
 614      * @param mapper a function extracting the property to be summed
 615      * @return a {@code Collector} that produces the sum of a derived property
 616      */
 617     public static <T> Collector<T, ?, Double>
 618     averagingInt(ToIntFunction<? super T> mapper) {
 619         return new CollectorImpl<>(
 620                 () -> new long[2],
 621                 (a, t) -> { a[0] += mapper.applyAsInt(t); a[1]++; },
 622                 (a, b) -> { a[0] += b[0]; a[1] += b[1]; return a; },
 623                 a -> (a[1] == 0) ? 0.0d : (double) a[0] / a[1], CH_NOID);
 624     }
 625 
 626     /**
 627      * Returns a {@code Collector} that produces the arithmetic mean of a long-valued
 628      * function applied to the input elements.  If no elements are present,
 629      * the result is 0.
 630      *
 631      * @param <T> the type of the input elements
 632      * @param mapper a function extracting the property to be summed
 633      * @return a {@code Collector} that produces the sum of a derived property
 634      */
 635     public static <T> Collector<T, ?, Double>
 636     averagingLong(ToLongFunction<? super T> mapper) {
 637         return new CollectorImpl<>(
 638                 () -> new long[2],
 639                 (a, t) -> { a[0] += mapper.applyAsLong(t); a[1]++; },
 640                 (a, b) -> { a[0] += b[0]; a[1] += b[1]; return a; },
 641                 a -> (a[1] == 0) ? 0.0d : (double) a[0] / a[1], CH_NOID);
 642     }
 643 
 644     /**
 645      * Returns a {@code Collector} that produces the arithmetic mean of a double-valued
 646      * function applied to the input elements.  If no elements are present,
 647      * the result is 0.
 648      *
 649      * <p>The average returned can vary depending upon the order in which
 650      * values are recorded, due to accumulated rounding error in
 651      * addition of values of differing magnitudes. Values sorted by increasing
 652      * absolute magnitude tend to yield more accurate results.  If any recorded
 653      * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 654      * average will be {@code NaN}.
 655      *
 656      * @implNote The {@code double} format can represent all
 657      * consecutive integers in the range -2<sup>53</sup> to
 658      * 2<sup>53</sup>. If the pipeline has more than 2<sup>53</sup>
 659      * values, the divisor in the average computation will saturate at
 660      * 2<sup>53</sup>, leading to additional numerical errors.
 661      *
 662      * @param <T> the type of the input elements
 663      * @param mapper a function extracting the property to be summed
 664      * @return a {@code Collector} that produces the sum of a derived property
 665      */
 666     public static <T> Collector<T, ?, Double>
 667     averagingDouble(ToDoubleFunction<? super T> mapper) {
 668         /*
 669          * In the arrays allocated for the collect operation, index 0
 670          * holds the high-order bits of the running sum, index 1 holds
 671          * the low-order bits of the sum computed via compensated
 672          * summation, and index 2 holds the number of values seen.
 673          */
 674         return new CollectorImpl<>(
 675                 () -> new double[4],
 676                 (a, t) -> { sumWithCompensation(a, mapper.applyAsDouble(t)); a[2]++; a[3]+= mapper.applyAsDouble(t);},
 677                 (a, b) -> { sumWithCompensation(a, b[0]); sumWithCompensation(a, b[1]); a[2] += b[2]; a[3] += b[3]; return a; },
 678                 a -> (a[2] == 0) ? 0.0d : (computeFinalSum(a) / a[2]),
 679                 CH_NOID);
 680     }
 681 
 682     /**
 683      * Returns a {@code Collector} which performs a reduction of its
 684      * input elements under a specified {@code BinaryOperator} using the
 685      * provided identity.
 686      *
 687      * @apiNote
 688      * The {@code reducing()} collectors are most useful when used in a
 689      * multi-level reduction, downstream of {@code groupingBy} or
 690      * {@code partitioningBy}.  To perform a simple reduction on a stream,
 691      * use {@link Stream#reduce(Object, BinaryOperator)}} instead.
 692      *
 693      * @param <T> element type for the input and output of the reduction
 694      * @param identity the identity value for the reduction (also, the value
 695      *                 that is returned when there are no input elements)
 696      * @param op a {@code BinaryOperator<T>} used to reduce the input elements
 697      * @return a {@code Collector} which implements the reduction operation
 698      *
 699      * @see #reducing(BinaryOperator)
 700      * @see #reducing(Object, Function, BinaryOperator)
 701      */
 702     public static <T> Collector<T, ?, T>
 703     reducing(T identity, BinaryOperator<T> op) {
 704         return new CollectorImpl<>(
 705                 boxSupplier(identity),
 706                 (a, t) -> { a[0] = op.apply(a[0], t); },
 707                 (a, b) -> { a[0] = op.apply(a[0], b[0]); return a; },
 708                 a -> a[0],
 709                 CH_NOID);
 710     }
 711 
 712     @SuppressWarnings("unchecked")
 713     private static <T> Supplier<T[]> boxSupplier(T identity) {
 714         return () -> (T[]) new Object[] { identity };
 715     }
 716 
 717     /**
 718      * Returns a {@code Collector} which performs a reduction of its
 719      * input elements under a specified {@code BinaryOperator}.  The result
 720      * is described as an {@code Optional<T>}.
 721      *
 722      * @apiNote
 723      * The {@code reducing()} collectors are most useful when used in a
 724      * multi-level reduction, downstream of {@code groupingBy} or
 725      * {@code partitioningBy}.  To perform a simple reduction on a stream,
 726      * use {@link Stream#reduce(BinaryOperator)} instead.
 727      *
 728      * <p>For example, given a stream of {@code Person}, to calculate tallest
 729      * person in each city:
 730      * <pre>{@code
 731      *     Comparator<Person> byHeight = Comparator.comparing(Person::getHeight);
 732      *     Map<City, Optional<Person>> tallestByCity
 733      *         = people.stream().collect(groupingBy(Person::getCity, reducing(BinaryOperator.maxBy(byHeight))));
 734      * }</pre>
 735      *
 736      * @param <T> element type for the input and output of the reduction
 737      * @param op a {@code BinaryOperator<T>} used to reduce the input elements
 738      * @return a {@code Collector} which implements the reduction operation
 739      *
 740      * @see #reducing(Object, BinaryOperator)
 741      * @see #reducing(Object, Function, BinaryOperator)
 742      */
 743     public static <T> Collector<T, ?, Optional<T>>
 744     reducing(BinaryOperator<T> op) {
 745         class OptionalBox implements Consumer<T> {
 746             T value = null;
 747             boolean present = false;
 748 
 749             @Override
 750             public void accept(T t) {
 751                 if (present) {
 752                     value = op.apply(value, t);
 753                 }
 754                 else {
 755                     value = t;
 756                     present = true;
 757                 }
 758             }
 759         }
 760 
 761         return new CollectorImpl<T, OptionalBox, Optional<T>>(
 762                 OptionalBox::new, OptionalBox::accept,
 763                 (a, b) -> { if (b.present) a.accept(b.value); return a; },
 764                 a -> Optional.ofNullable(a.value), CH_NOID);
 765     }
 766 
 767     /**
 768      * Returns a {@code Collector} which performs a reduction of its
 769      * input elements under a specified mapping function and
 770      * {@code BinaryOperator}. This is a generalization of
 771      * {@link #reducing(Object, BinaryOperator)} which allows a transformation
 772      * of the elements before reduction.
 773      *
 774      * @apiNote
 775      * The {@code reducing()} collectors are most useful when used in a
 776      * multi-level reduction, downstream of {@code groupingBy} or
 777      * {@code partitioningBy}.  To perform a simple map-reduce on a stream,
 778      * use {@link Stream#map(Function)} and {@link Stream#reduce(Object, BinaryOperator)}
 779      * instead.
 780      *
 781      * <p>For example, given a stream of {@code Person}, to calculate the longest
 782      * last name of residents in each city:
 783      * <pre>{@code
 784      *     Comparator<String> byLength = Comparator.comparing(String::length);
 785      *     Map<City, String> longestLastNameByCity
 786      *         = people.stream().collect(groupingBy(Person::getCity,
 787      *                                              reducing("", Person::getLastName, BinaryOperator.maxBy(byLength))));
 788      * }</pre>
 789      *
 790      * @param <T> the type of the input elements
 791      * @param <U> the type of the mapped values
 792      * @param identity the identity value for the reduction (also, the value
 793      *                 that is returned when there are no input elements)
 794      * @param mapper a mapping function to apply to each input value
 795      * @param op a {@code BinaryOperator<U>} used to reduce the mapped values
 796      * @return a {@code Collector} implementing the map-reduce operation
 797      *
 798      * @see #reducing(Object, BinaryOperator)
 799      * @see #reducing(BinaryOperator)
 800      */
 801     public static <T, U>
 802     Collector<T, ?, U> reducing(U identity,
 803                                 Function<? super T, ? extends U> mapper,
 804                                 BinaryOperator<U> op) {
 805         return new CollectorImpl<>(
 806                 boxSupplier(identity),
 807                 (a, t) -> { a[0] = op.apply(a[0], mapper.apply(t)); },
 808                 (a, b) -> { a[0] = op.apply(a[0], b[0]); return a; },
 809                 a -> a[0], CH_NOID);
 810     }
 811 
 812     /**
 813      * Returns a {@code Collector} implementing a "group by" operation on
 814      * input elements of type {@code T}, grouping elements according to a
 815      * classification function, and returning the results in a {@code Map}.
 816      *
 817      * <p>The classification function maps elements to some key type {@code K}.
 818      * The collector produces a {@code Map<K, List<T>>} whose keys are the
 819      * values resulting from applying the classification function to the input
 820      * elements, and whose corresponding values are {@code List}s containing the
 821      * input elements which map to the associated key under the classification
 822      * function.
 823      *
 824      * <p>There are no guarantees on the type, mutability, serializability, or
 825      * thread-safety of the {@code Map} or {@code List} objects returned.
 826      * @implSpec
 827      * This produces a result similar to:
 828      * <pre>{@code
 829      *     groupingBy(classifier, toList());
 830      * }</pre>
 831      *
 832      * @implNote
 833      * The returned {@code Collector} is not concurrent.  For parallel stream
 834      * pipelines, the {@code combiner} function operates by merging the keys
 835      * from one map into another, which can be an expensive operation.  If
 836      * preservation of the order in which elements appear in the resulting {@code Map}
 837      * collector is not required, using {@link #groupingByConcurrent(Function)}
 838      * may offer better parallel performance.
 839      *
 840      * @param <T> the type of the input elements
 841      * @param <K> the type of the keys
 842      * @param classifier the classifier function mapping input elements to keys
 843      * @return a {@code Collector} implementing the group-by operation
 844      *
 845      * @see #groupingBy(Function, Collector)
 846      * @see #groupingBy(Function, Supplier, Collector)
 847      * @see #groupingByConcurrent(Function)
 848      */
 849     public static <T, K> Collector<T, ?, Map<K, List<T>>>
 850     groupingBy(Function<? super T, ? extends K> classifier) {
 851         return groupingBy(classifier, toList());
 852     }
 853 
 854     /**
 855      * Returns a {@code Collector} implementing a cascaded "group by" operation
 856      * on input elements of type {@code T}, grouping elements according to a
 857      * classification function, and then performing a reduction operation on
 858      * the values associated with a given key using the specified downstream
 859      * {@code Collector}.
 860      *
 861      * <p>The classification function maps elements to some key type {@code K}.
 862      * The downstream collector operates on elements of type {@code T} and
 863      * produces a result of type {@code D}. The resulting collector produces a
 864      * {@code Map<K, D>}.
 865      *
 866      * <p>There are no guarantees on the type, mutability,
 867      * serializability, or thread-safety of the {@code Map} returned.
 868      *
 869      * <p>For example, to compute the set of last names of people in each city:
 870      * <pre>{@code
 871      *     Map<City, Set<String>> namesByCity
 872      *         = people.stream().collect(groupingBy(Person::getCity,
 873      *                                              mapping(Person::getLastName, toSet())));
 874      * }</pre>
 875      *
 876      * @implNote
 877      * The returned {@code Collector} is not concurrent.  For parallel stream
 878      * pipelines, the {@code combiner} function operates by merging the keys
 879      * from one map into another, which can be an expensive operation.  If
 880      * preservation of the order in which elements are presented to the downstream
 881      * collector is not required, using {@link #groupingByConcurrent(Function, Collector)}
 882      * may offer better parallel performance.
 883      *
 884      * @param <T> the type of the input elements
 885      * @param <K> the type of the keys
 886      * @param <A> the intermediate accumulation type of the downstream collector
 887      * @param <D> the result type of the downstream reduction
 888      * @param classifier a classifier function mapping input elements to keys
 889      * @param downstream a {@code Collector} implementing the downstream reduction
 890      * @return a {@code Collector} implementing the cascaded group-by operation
 891      * @see #groupingBy(Function)
 892      *
 893      * @see #groupingBy(Function, Supplier, Collector)
 894      * @see #groupingByConcurrent(Function, Collector)
 895      */
 896     public static <T, K, A, D>
 897     Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,
 898                                           Collector<? super T, A, D> downstream) {
 899         return groupingBy(classifier, HashMap::new, downstream);
 900     }
 901 
 902     /**
 903      * Returns a {@code Collector} implementing a cascaded "group by" operation
 904      * on input elements of type {@code T}, grouping elements according to a
 905      * classification function, and then performing a reduction operation on
 906      * the values associated with a given key using the specified downstream
 907      * {@code Collector}.  The {@code Map} produced by the Collector is created
 908      * with the supplied factory function.
 909      *
 910      * <p>The classification function maps elements to some key type {@code K}.
 911      * The downstream collector operates on elements of type {@code T} and
 912      * produces a result of type {@code D}. The resulting collector produces a
 913      * {@code Map<K, D>}.
 914      *
 915      * <p>For example, to compute the set of last names of people in each city,
 916      * where the city names are sorted:
 917      * <pre>{@code
 918      *     Map<City, Set<String>> namesByCity
 919      *         = people.stream().collect(groupingBy(Person::getCity, TreeMap::new,
 920      *                                              mapping(Person::getLastName, toSet())));
 921      * }</pre>
 922      *
 923      * @implNote
 924      * The returned {@code Collector} is not concurrent.  For parallel stream
 925      * pipelines, the {@code combiner} function operates by merging the keys
 926      * from one map into another, which can be an expensive operation.  If
 927      * preservation of the order in which elements are presented to the downstream
 928      * collector is not required, using {@link #groupingByConcurrent(Function, Supplier, Collector)}
 929      * may offer better parallel performance.
 930      *
 931      * @param <T> the type of the input elements
 932      * @param <K> the type of the keys
 933      * @param <A> the intermediate accumulation type of the downstream collector
 934      * @param <D> the result type of the downstream reduction
 935      * @param <M> the type of the resulting {@code Map}
 936      * @param classifier a classifier function mapping input elements to keys
 937      * @param downstream a {@code Collector} implementing the downstream reduction
 938      * @param mapFactory a function which, when called, produces a new empty
 939      *                   {@code Map} of the desired type
 940      * @return a {@code Collector} implementing the cascaded group-by operation
 941      *
 942      * @see #groupingBy(Function, Collector)
 943      * @see #groupingBy(Function)
 944      * @see #groupingByConcurrent(Function, Supplier, Collector)
 945      */
 946     public static <T, K, D, A, M extends Map<K, D>>
 947     Collector<T, ?, M> groupingBy(Function<? super T, ? extends K> classifier,
 948                                   Supplier<M> mapFactory,
 949                                   Collector<? super T, A, D> downstream) {
 950         Supplier<A> downstreamSupplier = downstream.supplier();
 951         BiConsumer<A, ? super T> downstreamAccumulator = downstream.accumulator();
 952         BiConsumer<Map<K, A>, T> accumulator = (m, t) -> {
 953             K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key");
 954             A container = m.computeIfAbsent(key, k -> downstreamSupplier.get());
 955             downstreamAccumulator.accept(container, t);
 956         };
 957         BinaryOperator<Map<K, A>> merger = Collectors.<K, A, Map<K, A>>mapMerger(downstream.combiner());
 958         @SuppressWarnings("unchecked")
 959         Supplier<Map<K, A>> mangledFactory = (Supplier<Map<K, A>>) mapFactory;
 960 
 961         if (downstream.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)) {
 962             return new CollectorImpl<>(mangledFactory, accumulator, merger, CH_ID);
 963         }
 964         else {
 965             @SuppressWarnings("unchecked")
 966             Function<A, A> downstreamFinisher = (Function<A, A>) downstream.finisher();
 967             Function<Map<K, A>, M> finisher = intermediate -> {
 968                 intermediate.replaceAll((k, v) -> downstreamFinisher.apply(v));
 969                 @SuppressWarnings("unchecked")
 970                 M castResult = (M) intermediate;
 971                 return castResult;
 972             };
 973             return new CollectorImpl<>(mangledFactory, accumulator, merger, finisher, CH_NOID);
 974         }
 975     }
 976 
 977     /**
 978      * Returns a concurrent {@code Collector} implementing a "group by"
 979      * operation on input elements of type {@code T}, grouping elements
 980      * according to a classification function.
 981      *
 982      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
 983      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
 984      *
 985      * <p>The classification function maps elements to some key type {@code K}.
 986      * The collector produces a {@code ConcurrentMap<K, List<T>>} whose keys are the
 987      * values resulting from applying the classification function to the input
 988      * elements, and whose corresponding values are {@code List}s containing the
 989      * input elements which map to the associated key under the classification
 990      * function.
 991      *
 992      * <p>There are no guarantees on the type, mutability, or serializability
 993      * of the {@code Map} or {@code List} objects returned, or of the
 994      * thread-safety of the {@code List} objects returned.
 995      * @implSpec
 996      * This produces a result similar to:
 997      * <pre>{@code
 998      *     groupingByConcurrent(classifier, toList());
 999      * }</pre>
1000      *
1001      * @param <T> the type of the input elements
1002      * @param <K> the type of the keys
1003      * @param classifier a classifier function mapping input elements to keys
1004      * @return a concurrent, unordered {@code Collector} implementing the group-by operation
1005      *
1006      * @see #groupingBy(Function)
1007      * @see #groupingByConcurrent(Function, Collector)
1008      * @see #groupingByConcurrent(Function, Supplier, Collector)
1009      */
1010     public static <T, K>
1011     Collector<T, ?, ConcurrentMap<K, List<T>>>
1012     groupingByConcurrent(Function<? super T, ? extends K> classifier) {
1013         return groupingByConcurrent(classifier, ConcurrentHashMap::new, toList());
1014     }
1015 
1016     /**
1017      * Returns a concurrent {@code Collector} implementing a cascaded "group by"
1018      * operation on input elements of type {@code T}, grouping elements
1019      * according to a classification function, and then performing a reduction
1020      * operation on the values associated with a given key using the specified
1021      * downstream {@code Collector}.
1022      *
1023      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
1024      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
1025      *
1026      * <p>The classification function maps elements to some key type {@code K}.
1027      * The downstream collector operates on elements of type {@code T} and
1028      * produces a result of type {@code D}. The resulting collector produces a
1029      * {@code Map<K, D>}.
1030      *
1031      * <p>For example, to compute the set of last names of people in each city,
1032      * where the city names are sorted:
1033      * <pre>{@code
1034      *     ConcurrentMap<City, Set<String>> namesByCity
1035      *         = people.stream().collect(groupingByConcurrent(Person::getCity,
1036      *                                                        mapping(Person::getLastName, toSet())));
1037      * }</pre>
1038      *
1039      * @param <T> the type of the input elements
1040      * @param <K> the type of the keys
1041      * @param <A> the intermediate accumulation type of the downstream collector
1042      * @param <D> the result type of the downstream reduction
1043      * @param classifier a classifier function mapping input elements to keys
1044      * @param downstream a {@code Collector} implementing the downstream reduction
1045      * @return a concurrent, unordered {@code Collector} implementing the cascaded group-by operation
1046      *
1047      * @see #groupingBy(Function, Collector)
1048      * @see #groupingByConcurrent(Function)
1049      * @see #groupingByConcurrent(Function, Supplier, Collector)
1050      */
1051     public static <T, K, A, D>
1052     Collector<T, ?, ConcurrentMap<K, D>> groupingByConcurrent(Function<? super T, ? extends K> classifier,
1053                                                               Collector<? super T, A, D> downstream) {
1054         return groupingByConcurrent(classifier, ConcurrentHashMap::new, downstream);
1055     }
1056 
1057     /**
1058      * Returns a concurrent {@code Collector} implementing a cascaded "group by"
1059      * operation on input elements of type {@code T}, grouping elements
1060      * according to a classification function, and then performing a reduction
1061      * operation on the values associated with a given key using the specified
1062      * downstream {@code Collector}.  The {@code ConcurrentMap} produced by the
1063      * Collector is created with the supplied factory function.
1064      *
1065      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
1066      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
1067      *
1068      * <p>The classification function maps elements to some key type {@code K}.
1069      * The downstream collector operates on elements of type {@code T} and
1070      * produces a result of type {@code D}. The resulting collector produces a
1071      * {@code Map<K, D>}.
1072      *
1073      * <p>For example, to compute the set of last names of people in each city,
1074      * where the city names are sorted:
1075      * <pre>{@code
1076      *     ConcurrentMap<City, Set<String>> namesByCity
1077      *         = people.stream().collect(groupingBy(Person::getCity, ConcurrentSkipListMap::new,
1078      *                                              mapping(Person::getLastName, toSet())));
1079      * }</pre>
1080      *
1081      *
1082      * @param <T> the type of the input elements
1083      * @param <K> the type of the keys
1084      * @param <A> the intermediate accumulation type of the downstream collector
1085      * @param <D> the result type of the downstream reduction
1086      * @param <M> the type of the resulting {@code ConcurrentMap}
1087      * @param classifier a classifier function mapping input elements to keys
1088      * @param downstream a {@code Collector} implementing the downstream reduction
1089      * @param mapFactory a function which, when called, produces a new empty
1090      *                   {@code ConcurrentMap} of the desired type
1091      * @return a concurrent, unordered {@code Collector} implementing the cascaded group-by operation
1092      *
1093      * @see #groupingByConcurrent(Function)
1094      * @see #groupingByConcurrent(Function, Collector)
1095      * @see #groupingBy(Function, Supplier, Collector)
1096      */
1097     public static <T, K, A, D, M extends ConcurrentMap<K, D>>
1098     Collector<T, ?, M> groupingByConcurrent(Function<? super T, ? extends K> classifier,
1099                                             Supplier<M> mapFactory,
1100                                             Collector<? super T, A, D> downstream) {
1101         Supplier<A> downstreamSupplier = downstream.supplier();
1102         BiConsumer<A, ? super T> downstreamAccumulator = downstream.accumulator();
1103         BinaryOperator<ConcurrentMap<K, A>> merger = Collectors.<K, A, ConcurrentMap<K, A>>mapMerger(downstream.combiner());
1104         @SuppressWarnings("unchecked")
1105         Supplier<ConcurrentMap<K, A>> mangledFactory = (Supplier<ConcurrentMap<K, A>>) mapFactory;
1106         BiConsumer<ConcurrentMap<K, A>, T> accumulator;
1107         if (downstream.characteristics().contains(Collector.Characteristics.CONCURRENT)) {
1108             accumulator = (m, t) -> {
1109                 K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key");
1110                 A resultContainer = m.computeIfAbsent(key, k -> downstreamSupplier.get());
1111                 downstreamAccumulator.accept(resultContainer, t);
1112             };
1113         }
1114         else {
1115             accumulator = (m, t) -> {
1116                 K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key");
1117                 A resultContainer = m.computeIfAbsent(key, k -> downstreamSupplier.get());
1118                 synchronized (resultContainer) {
1119                     downstreamAccumulator.accept(resultContainer, t);
1120                 }
1121             };
1122         }
1123 
1124         if (downstream.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)) {
1125             return new CollectorImpl<>(mangledFactory, accumulator, merger, CH_CONCURRENT_ID);
1126         }
1127         else {
1128             @SuppressWarnings("unchecked")
1129             Function<A, A> downstreamFinisher = (Function<A, A>) downstream.finisher();
1130             Function<ConcurrentMap<K, A>, M> finisher = intermediate -> {
1131                 intermediate.replaceAll((k, v) -> downstreamFinisher.apply(v));
1132                 @SuppressWarnings("unchecked")
1133                 M castResult = (M) intermediate;
1134                 return castResult;
1135             };
1136             return new CollectorImpl<>(mangledFactory, accumulator, merger, finisher, CH_CONCURRENT_NOID);
1137         }
1138     }
1139 
1140     /**
1141      * Returns a {@code Collector} which partitions the input elements according
1142      * to a {@code Predicate}, and organizes them into a
1143      * {@code Map<Boolean, List<T>>}.
1144      *
1145      * There are no guarantees on the type, mutability,
1146      * serializability, or thread-safety of the {@code Map} returned.
1147      *
1148      * @param <T> the type of the input elements
1149      * @param predicate a predicate used for classifying input elements
1150      * @return a {@code Collector} implementing the partitioning operation
1151      *
1152      * @see #partitioningBy(Predicate, Collector)
1153      */
1154     public static <T>
1155     Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate) {
1156         return partitioningBy(predicate, toList());
1157     }
1158 
1159     /**
1160      * Returns a {@code Collector} which partitions the input elements according
1161      * to a {@code Predicate}, reduces the values in each partition according to
1162      * another {@code Collector}, and organizes them into a
1163      * {@code Map<Boolean, D>} whose values are the result of the downstream
1164      * reduction.
1165      *
1166      * <p>There are no guarantees on the type, mutability,
1167      * serializability, or thread-safety of the {@code Map} returned.
1168      *
1169      * @param <T> the type of the input elements
1170      * @param <A> the intermediate accumulation type of the downstream collector
1171      * @param <D> the result type of the downstream reduction
1172      * @param predicate a predicate used for classifying input elements
1173      * @param downstream a {@code Collector} implementing the downstream
1174      *                   reduction
1175      * @return a {@code Collector} implementing the cascaded partitioning
1176      *         operation
1177      *
1178      * @see #partitioningBy(Predicate)
1179      */
1180     public static <T, D, A>
1181     Collector<T, ?, Map<Boolean, D>> partitioningBy(Predicate<? super T> predicate,
1182                                                     Collector<? super T, A, D> downstream) {
1183         BiConsumer<A, ? super T> downstreamAccumulator = downstream.accumulator();
1184         BiConsumer<Partition<A>, T> accumulator = (result, t) ->
1185                 downstreamAccumulator.accept(predicate.test(t) ? result.forTrue : result.forFalse, t);
1186         BinaryOperator<A> op = downstream.combiner();
1187         BinaryOperator<Partition<A>> merger = (left, right) ->
1188                 new Partition<>(op.apply(left.forTrue, right.forTrue),
1189                                 op.apply(left.forFalse, right.forFalse));
1190         Supplier<Partition<A>> supplier = () ->
1191                 new Partition<>(downstream.supplier().get(),
1192                                 downstream.supplier().get());
1193         if (downstream.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)) {
1194             return new CollectorImpl<>(supplier, accumulator, merger, CH_ID);
1195         }
1196         else {
1197             Function<Partition<A>, Map<Boolean, D>> finisher = par ->
1198                     new Partition<>(downstream.finisher().apply(par.forTrue),
1199                                     downstream.finisher().apply(par.forFalse));
1200             return new CollectorImpl<>(supplier, accumulator, merger, finisher, CH_NOID);
1201         }
1202     }
1203 
1204     /**
1205      * Returns a {@code Collector} that accumulates elements into a
1206      * {@code Map} whose keys and values are the result of applying the provided
1207      * mapping functions to the input elements.
1208      *
1209      * <p>If the mapped keys contains duplicates (according to
1210      * {@link Object#equals(Object)}), an {@code IllegalStateException} is
1211      * thrown when the collection operation is performed.  If the mapped keys
1212      * may have duplicates, use {@link #toMap(Function, Function, BinaryOperator)}
1213      * instead.
1214      *
1215      * @apiNote
1216      * It is common for either the key or the value to be the input elements.
1217      * In this case, the utility method
1218      * {@link java.util.function.Function#identity()} may be helpful.
1219      * For example, the following produces a {@code Map} mapping
1220      * students to their grade point average:
1221      * <pre>{@code
1222      *     Map<Student, Double> studentToGPA
1223      *         students.stream().collect(toMap(Function.identity(),
1224      *                                         student -> computeGPA(student)));
1225      * }</pre>
1226      * And the following produces a {@code Map} mapping a unique identifier to
1227      * students:
1228      * <pre>{@code
1229      *     Map<String, Student> studentIdToStudent
1230      *         students.stream().collect(toMap(Student::getId,
1231      *                                         Function.identity());
1232      * }</pre>
1233      *
1234      * @implNote
1235      * The returned {@code Collector} is not concurrent.  For parallel stream
1236      * pipelines, the {@code combiner} function operates by merging the keys
1237      * from one map into another, which can be an expensive operation.  If it is
1238      * not required that results are inserted into the {@code Map} in encounter
1239      * order, using {@link #toConcurrentMap(Function, Function)}
1240      * may offer better parallel performance.
1241      *
1242      * @param <T> the type of the input elements
1243      * @param <K> the output type of the key mapping function
1244      * @param <U> the output type of the value mapping function
1245      * @param keyMapper a mapping function to produce keys
1246      * @param valueMapper a mapping function to produce values
1247      * @return a {@code Collector} which collects elements into a {@code Map}
1248      * whose keys and values are the result of applying mapping functions to
1249      * the input elements
1250      *
1251      * @see #toMap(Function, Function, BinaryOperator)
1252      * @see #toMap(Function, Function, BinaryOperator, Supplier)
1253      * @see #toConcurrentMap(Function, Function)
1254      */
1255     public static <T, K, U>
1256     Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
1257                                     Function<? super T, ? extends U> valueMapper) {
1258         return new CollectorImpl<>(HashMap::new,
1259                                    uniqKeysMapAccumulator(keyMapper, valueMapper),
1260                                    uniqKeysMapMerger(),
1261                                    CH_ID);
1262     }
1263 
1264     /**
1265      * Returns a {@code Collector} that accumulates elements into a
1266      * {@code Map} whose keys and values are the result of applying the provided
1267      * mapping functions to the input elements.
1268      *
1269      * <p>If the mapped
1270      * keys contains duplicates (according to {@link Object#equals(Object)}),
1271      * the value mapping function is applied to each equal element, and the
1272      * results are merged using the provided merging function.
1273      *
1274      * @apiNote
1275      * There are multiple ways to deal with collisions between multiple elements
1276      * mapping to the same key.  The other forms of {@code toMap} simply use
1277      * a merge function that throws unconditionally, but you can easily write
1278      * more flexible merge policies.  For example, if you have a stream
1279      * of {@code Person}, and you want to produce a "phone book" mapping name to
1280      * address, but it is possible that two persons have the same name, you can
1281      * do as follows to gracefully deals with these collisions, and produce a
1282      * {@code Map} mapping names to a concatenated list of addresses:
1283      * <pre>{@code
1284      *     Map<String, String> phoneBook
1285      *         people.stream().collect(toMap(Person::getName,
1286      *                                       Person::getAddress,
1287      *                                       (s, a) -> s + ", " + a));
1288      * }</pre>
1289      *
1290      * @implNote
1291      * The returned {@code Collector} is not concurrent.  For parallel stream
1292      * pipelines, the {@code combiner} function operates by merging the keys
1293      * from one map into another, which can be an expensive operation.  If it is
1294      * not required that results are merged into the {@code Map} in encounter
1295      * order, using {@link #toConcurrentMap(Function, Function, BinaryOperator)}
1296      * may offer better parallel performance.
1297      *
1298      * @param <T> the type of the input elements
1299      * @param <K> the output type of the key mapping function
1300      * @param <U> the output type of the value mapping function
1301      * @param keyMapper a mapping function to produce keys
1302      * @param valueMapper a mapping function to produce values
1303      * @param mergeFunction a merge function, used to resolve collisions between
1304      *                      values associated with the same key, as supplied
1305      *                      to {@link Map#merge(Object, Object, BiFunction)}
1306      * @return a {@code Collector} which collects elements into a {@code Map}
1307      * whose keys are the result of applying a key mapping function to the input
1308      * elements, and whose values are the result of applying a value mapping
1309      * function to all input elements equal to the key and combining them
1310      * using the merge function
1311      *
1312      * @see #toMap(Function, Function)
1313      * @see #toMap(Function, Function, BinaryOperator, Supplier)
1314      * @see #toConcurrentMap(Function, Function, BinaryOperator)
1315      */
1316     public static <T, K, U>
1317     Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
1318                                     Function<? super T, ? extends U> valueMapper,
1319                                     BinaryOperator<U> mergeFunction) {
1320         return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
1321     }
1322 
1323     /**
1324      * Returns a {@code Collector} that accumulates elements into a
1325      * {@code Map} whose keys and values are the result of applying the provided
1326      * mapping functions to the input elements.
1327      *
1328      * <p>If the mapped
1329      * keys contains duplicates (according to {@link Object#equals(Object)}),
1330      * the value mapping function is applied to each equal element, and the
1331      * results are merged using the provided merging function.  The {@code Map}
1332      * is created by a provided supplier function.
1333      *
1334      * @implNote
1335      * The returned {@code Collector} is not concurrent.  For parallel stream
1336      * pipelines, the {@code combiner} function operates by merging the keys
1337      * from one map into another, which can be an expensive operation.  If it is
1338      * not required that results are merged into the {@code Map} in encounter
1339      * order, using {@link #toConcurrentMap(Function, Function, BinaryOperator, Supplier)}
1340      * may offer better parallel performance.
1341      *
1342      * @param <T> the type of the input elements
1343      * @param <K> the output type of the key mapping function
1344      * @param <U> the output type of the value mapping function
1345      * @param <M> the type of the resulting {@code Map}
1346      * @param keyMapper a mapping function to produce keys
1347      * @param valueMapper a mapping function to produce values
1348      * @param mergeFunction a merge function, used to resolve collisions between
1349      *                      values associated with the same key, as supplied
1350      *                      to {@link Map#merge(Object, Object, BiFunction)}
1351      * @param mapSupplier a function which returns a new, empty {@code Map} into
1352      *                    which the results will be inserted
1353      * @return a {@code Collector} which collects elements into a {@code Map}
1354      * whose keys are the result of applying a key mapping function to the input
1355      * elements, and whose values are the result of applying a value mapping
1356      * function to all input elements equal to the key and combining them
1357      * using the merge function
1358      *
1359      * @see #toMap(Function, Function)
1360      * @see #toMap(Function, Function, BinaryOperator)
1361      * @see #toConcurrentMap(Function, Function, BinaryOperator, Supplier)
1362      */
1363     public static <T, K, U, M extends Map<K, U>>
1364     Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
1365                                 Function<? super T, ? extends U> valueMapper,
1366                                 BinaryOperator<U> mergeFunction,
1367                                 Supplier<M> mapSupplier) {
1368         BiConsumer<M, T> accumulator
1369                 = (map, element) -> map.merge(keyMapper.apply(element),
1370                                               valueMapper.apply(element), mergeFunction);
1371         return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID);
1372     }
1373 
1374     /**
1375      * Returns a concurrent {@code Collector} that accumulates elements into a
1376      * {@code ConcurrentMap} whose keys and values are the result of applying
1377      * the provided mapping functions to the input elements.
1378      *
1379      * <p>If the mapped keys contains duplicates (according to
1380      * {@link Object#equals(Object)}), an {@code IllegalStateException} is
1381      * thrown when the collection operation is performed.  If the mapped keys
1382      * may have duplicates, use
1383      * {@link #toConcurrentMap(Function, Function, BinaryOperator)} instead.
1384      *
1385      * @apiNote
1386      * It is common for either the key or the value to be the input elements.
1387      * In this case, the utility method
1388      * {@link java.util.function.Function#identity()} may be helpful.
1389      * For example, the following produces a {@code Map} mapping
1390      * students to their grade point average:
1391      * <pre>{@code
1392      *     Map<Student, Double> studentToGPA
1393      *         students.stream().collect(toMap(Function.identity(),
1394      *                                         student -> computeGPA(student)));
1395      * }</pre>
1396      * And the following produces a {@code Map} mapping a unique identifier to
1397      * students:
1398      * <pre>{@code
1399      *     Map<String, Student> studentIdToStudent
1400      *         students.stream().collect(toConcurrentMap(Student::getId,
1401      *                                                   Function.identity());
1402      * }</pre>
1403      *
1404      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
1405      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
1406      *
1407      * @param <T> the type of the input elements
1408      * @param <K> the output type of the key mapping function
1409      * @param <U> the output type of the value mapping function
1410      * @param keyMapper the mapping function to produce keys
1411      * @param valueMapper the mapping function to produce values
1412      * @return a concurrent, unordered {@code Collector} which collects elements into a
1413      * {@code ConcurrentMap} whose keys are the result of applying a key mapping
1414      * function to the input elements, and whose values are the result of
1415      * applying a value mapping function to the input elements
1416      *
1417      * @see #toMap(Function, Function)
1418      * @see #toConcurrentMap(Function, Function, BinaryOperator)
1419      * @see #toConcurrentMap(Function, Function, BinaryOperator, Supplier)
1420      */
1421     public static <T, K, U>
1422     Collector<T, ?, ConcurrentMap<K,U>> toConcurrentMap(Function<? super T, ? extends K> keyMapper,
1423                                                         Function<? super T, ? extends U> valueMapper) {
1424         return new CollectorImpl<>(ConcurrentHashMap::new,
1425                                    uniqKeysMapAccumulator(keyMapper, valueMapper),
1426                                    uniqKeysMapMerger(),
1427                                    CH_CONCURRENT_ID);
1428     }
1429 
1430     /**
1431      * Returns a concurrent {@code Collector} that accumulates elements into a
1432      * {@code ConcurrentMap} whose keys and values are the result of applying
1433      * the provided mapping functions to the input elements.
1434      *
1435      * <p>If the mapped keys contains duplicates (according to {@link Object#equals(Object)}),
1436      * the value mapping function is applied to each equal element, and the
1437      * results are merged using the provided merging function.
1438      *
1439      * @apiNote
1440      * There are multiple ways to deal with collisions between multiple elements
1441      * mapping to the same key.  The other forms of {@code toConcurrentMap} simply use
1442      * a merge function that throws unconditionally, but you can easily write
1443      * more flexible merge policies.  For example, if you have a stream
1444      * of {@code Person}, and you want to produce a "phone book" mapping name to
1445      * address, but it is possible that two persons have the same name, you can
1446      * do as follows to gracefully deals with these collisions, and produce a
1447      * {@code Map} mapping names to a concatenated list of addresses:
1448      * <pre>{@code
1449      *     Map<String, String> phoneBook
1450      *         people.stream().collect(toConcurrentMap(Person::getName,
1451      *                                                 Person::getAddress,
1452      *                                                 (s, a) -> s + ", " + a));
1453      * }</pre>
1454      *
1455      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
1456      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
1457      *
1458      * @param <T> the type of the input elements
1459      * @param <K> the output type of the key mapping function
1460      * @param <U> the output type of the value mapping function
1461      * @param keyMapper a mapping function to produce keys
1462      * @param valueMapper a mapping function to produce values
1463      * @param mergeFunction a merge function, used to resolve collisions between
1464      *                      values associated with the same key, as supplied
1465      *                      to {@link Map#merge(Object, Object, BiFunction)}
1466      * @return a concurrent, unordered {@code Collector} which collects elements into a
1467      * {@code ConcurrentMap} whose keys are the result of applying a key mapping
1468      * function to the input elements, and whose values are the result of
1469      * applying a value mapping function to all input elements equal to the key
1470      * and combining them using the merge function
1471      *
1472      * @see #toConcurrentMap(Function, Function)
1473      * @see #toConcurrentMap(Function, Function, BinaryOperator, Supplier)
1474      * @see #toMap(Function, Function, BinaryOperator)
1475      */
1476     public static <T, K, U>
1477     Collector<T, ?, ConcurrentMap<K,U>>
1478     toConcurrentMap(Function<? super T, ? extends K> keyMapper,
1479                     Function<? super T, ? extends U> valueMapper,
1480                     BinaryOperator<U> mergeFunction) {
1481         return toConcurrentMap(keyMapper, valueMapper, mergeFunction, ConcurrentHashMap::new);
1482     }
1483 
1484     /**
1485      * Returns a concurrent {@code Collector} that accumulates elements into a
1486      * {@code ConcurrentMap} whose keys and values are the result of applying
1487      * the provided mapping functions to the input elements.
1488      *
1489      * <p>If the mapped keys contains duplicates (according to {@link Object#equals(Object)}),
1490      * the value mapping function is applied to each equal element, and the
1491      * results are merged using the provided merging function.  The
1492      * {@code ConcurrentMap} is created by a provided supplier function.
1493      *
1494      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
1495      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
1496      *
1497      * @param <T> the type of the input elements
1498      * @param <K> the output type of the key mapping function
1499      * @param <U> the output type of the value mapping function
1500      * @param <M> the type of the resulting {@code ConcurrentMap}
1501      * @param keyMapper a mapping function to produce keys
1502      * @param valueMapper a mapping function to produce values
1503      * @param mergeFunction a merge function, used to resolve collisions between
1504      *                      values associated with the same key, as supplied
1505      *                      to {@link Map#merge(Object, Object, BiFunction)}
1506      * @param mapSupplier a function which returns a new, empty {@code Map} into
1507      *                    which the results will be inserted
1508      * @return a concurrent, unordered {@code Collector} which collects elements into a
1509      * {@code ConcurrentMap} whose keys are the result of applying a key mapping
1510      * function to the input elements, and whose values are the result of
1511      * applying a value mapping function to all input elements equal to the key
1512      * and combining them using the merge function
1513      *
1514      * @see #toConcurrentMap(Function, Function)
1515      * @see #toConcurrentMap(Function, Function, BinaryOperator)
1516      * @see #toMap(Function, Function, BinaryOperator, Supplier)
1517      */
1518     public static <T, K, U, M extends ConcurrentMap<K, U>>
1519     Collector<T, ?, M> toConcurrentMap(Function<? super T, ? extends K> keyMapper,
1520                                        Function<? super T, ? extends U> valueMapper,
1521                                        BinaryOperator<U> mergeFunction,
1522                                        Supplier<M> mapSupplier) {
1523         BiConsumer<M, T> accumulator
1524                 = (map, element) -> map.merge(keyMapper.apply(element),
1525                                               valueMapper.apply(element), mergeFunction);
1526         return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_CONCURRENT_ID);
1527     }
1528 
1529     /**
1530      * Returns a {@code Collector} which applies an {@code int}-producing
1531      * mapping function to each input element, and returns summary statistics
1532      * for the resulting values.
1533      *
1534      * @param <T> the type of the input elements
1535      * @param mapper a mapping function to apply to each element
1536      * @return a {@code Collector} implementing the summary-statistics reduction
1537      *
1538      * @see #summarizingDouble(ToDoubleFunction)
1539      * @see #summarizingLong(ToLongFunction)
1540      */
1541     public static <T>
1542     Collector<T, ?, IntSummaryStatistics> summarizingInt(ToIntFunction<? super T> mapper) {
1543         return new CollectorImpl<T, IntSummaryStatistics, IntSummaryStatistics>(
1544                 IntSummaryStatistics::new,
1545                 (r, t) -> r.accept(mapper.applyAsInt(t)),
1546                 (l, r) -> { l.combine(r); return l; }, CH_ID);
1547     }
1548 
1549     /**
1550      * Returns a {@code Collector} which applies an {@code long}-producing
1551      * mapping function to each input element, and returns summary statistics
1552      * for the resulting values.
1553      *
1554      * @param <T> the type of the input elements
1555      * @param mapper the mapping function to apply to each element
1556      * @return a {@code Collector} implementing the summary-statistics reduction
1557      *
1558      * @see #summarizingDouble(ToDoubleFunction)
1559      * @see #summarizingInt(ToIntFunction)
1560      */
1561     public static <T>
1562     Collector<T, ?, LongSummaryStatistics> summarizingLong(ToLongFunction<? super T> mapper) {
1563         return new CollectorImpl<T, LongSummaryStatistics, LongSummaryStatistics>(
1564                 LongSummaryStatistics::new,
1565                 (r, t) -> r.accept(mapper.applyAsLong(t)),
1566                 (l, r) -> { l.combine(r); return l; }, CH_ID);
1567     }
1568 
1569     /**
1570      * Returns a {@code Collector} which applies an {@code double}-producing
1571      * mapping function to each input element, and returns summary statistics
1572      * for the resulting values.
1573      *
1574      * @param <T> the type of the input elements
1575      * @param mapper a mapping function to apply to each element
1576      * @return a {@code Collector} implementing the summary-statistics reduction
1577      *
1578      * @see #summarizingLong(ToLongFunction)
1579      * @see #summarizingInt(ToIntFunction)
1580      */
1581     public static <T>
1582     Collector<T, ?, DoubleSummaryStatistics> summarizingDouble(ToDoubleFunction<? super T> mapper) {
1583         return new CollectorImpl<T, DoubleSummaryStatistics, DoubleSummaryStatistics>(
1584                 DoubleSummaryStatistics::new,
1585                 (r, t) -> r.accept(mapper.applyAsDouble(t)),
1586                 (l, r) -> { l.combine(r); return l; }, CH_ID);
1587     }
1588 
1589     /**
1590      * Implementation class used by partitioningBy.
1591      */
1592     private static final class Partition<T>
1593             extends AbstractMap<Boolean, T>
1594             implements Map<Boolean, T> {
1595         final T forTrue;
1596         final T forFalse;
1597 
1598         Partition(T forTrue, T forFalse) {
1599             this.forTrue = forTrue;
1600             this.forFalse = forFalse;
1601         }
1602 
1603         @Override
1604         public Set<Map.Entry<Boolean, T>> entrySet() {
1605             return new AbstractSet<Map.Entry<Boolean, T>>() {
1606                 @Override
1607                 public Iterator<Map.Entry<Boolean, T>> iterator() {
1608                     Map.Entry<Boolean, T> falseEntry = new SimpleImmutableEntry<>(false, forFalse);
1609                     Map.Entry<Boolean, T> trueEntry = new SimpleImmutableEntry<>(true, forTrue);
1610                     return Arrays.asList(falseEntry, trueEntry).iterator();
1611                 }
1612 
1613                 @Override
1614                 public int size() {
1615                     return 2;
1616                 }
1617             };
1618         }
1619     }
1620 }