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.Collection;
  31 import java.util.Collections;
  32 import java.util.Comparator;
  33 import java.util.Comparators;
  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.NoSuchElementException;
  44 import java.util.Objects;
  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.BiFunction;
  50 import java.util.function.BinaryOperator;
  51 import java.util.function.Function;
  52 import java.util.function.Predicate;
  53 import java.util.function.Supplier;
  54 import java.util.function.ToDoubleFunction;
  55 import java.util.function.ToIntFunction;
  56 import java.util.function.ToLongFunction;
  57 
  58 /**
  59  * Implementations of {@link Collector} that implement various useful reduction
  60  * operations, such as accumulating elements into collections, summarizing
  61  * elements according to various criteria, etc.
  62  *
  63  * <p>The following are examples of using the predefined {@code Collector}
  64  * implementations in {@link Collectors} with the {@code Stream} API to perform
  65  * mutable reduction tasks:
  66  *
  67  * <pre>{@code
  68  *     // Accumulate elements into a List
  69  *     List<Person> list = people.collect(Collectors.toList());
  70  *
  71  *     // Accumulate elements into a TreeSet
  72  *     List<Person> list = people.collect(Collectors.toCollection(TreeSet::new));
  73  *
  74  *     // Convert elements to strings and concatenate them, separated by commas
  75  *     String joined = stream.map(Object::toString)
  76  *                           .collect(Collectors.toStringJoiner(", "))
  77  *                           .toString();
  78  *
  79  *     // Find highest-paid employee
  80  *     Employee highestPaid = employees.stream()
  81  *                                     .collect(Collectors.maxBy(Comparators.comparing(Employee::getSalary)));
  82  *
  83  *     // Group employees by department
  84  *     Map<Department, List<Employee>> byDept
  85  *         = employees.stream()
  86  *                    .collect(Collectors.groupingBy(Employee::getDepartment));
  87  *
  88  *     // Find highest-paid employee by department
  89  *     Map<Department, Employee> highestPaidByDept
  90  *         = employees.stream()
  91  *                    .collect(Collectors.groupingBy(Employee::getDepartment,
  92  *                                                   Collectors.maxBy(Comparators.comparing(Employee::getSalary))));
  93  *
  94  *     // Partition students into passing and failing
  95  *     Map<Boolean, List<Student>> passingFailing =
  96  *         students.stream()
  97  *                 .collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD);
  98  *
  99  * }</pre>
 100  *
 101  * TODO explanation of parallel collection
 102  *
 103  * @since 1.8
 104  */
 105 public final class Collectors {
 106 
 107     private static final Set<Collector.Characteristics> CH_CONCURRENT
 108             = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.CONCURRENT,
 109                                                      Collector.Characteristics.STRICTLY_MUTATIVE,
 110                                                      Collector.Characteristics.UNORDERED));
 111     private static final Set<Collector.Characteristics> CH_STRICT
 112             = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.STRICTLY_MUTATIVE));
 113     private static final Set<Collector.Characteristics> CH_STRICT_UNORDERED
 114             = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.STRICTLY_MUTATIVE,
 115                                                      Collector.Characteristics.UNORDERED));
 116 
 117     private Collectors() { }
 118 
 119     /**
 120      * Returns a merge function, suitable for use in
 121      * {@link Map#merge(Object, Object, BiFunction) Map.merge()} or
 122      * {@link #toMap(Function, Function, BinaryOperator) toMap()}, which always
 123      * throws {@code IllegalStateException}.  This can be used to enforce the
 124      * assumption that the elements being collected are distinct.
 125      *
 126      * @param <T> the type of input arguments to the merge function
 127      * @return a merge function which always throw {@code IllegalStateException}
 128      *
 129      * @see #firstWinsMerger()
 130      * @see #lastWinsMerger()
 131      */
 132     public static <T> BinaryOperator<T> throwingMerger() {
 133         return (u,v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); };
 134     }
 135 
 136     /**
 137      * Returns a merge function, suitable for use in
 138      * {@link Map#merge(Object, Object, BiFunction) Map.merge()} or
 139      * {@link #toMap(Function, Function, BinaryOperator) toMap()},
 140      * which implements a "first wins" policy.
 141      *
 142      * @param <T> the type of input arguments to the merge function
 143      * @return a merge function which always returns its first argument
 144      * @see #lastWinsMerger()
 145      * @see #throwingMerger()
 146      */
 147     public static <T> BinaryOperator<T> firstWinsMerger() {
 148         return (u,v) -> u;
 149     }
 150 
 151     /**
 152      * Returns a merge function, suitable for use in
 153      * {@link Map#merge(Object, Object, BiFunction) Map.merge()} or
 154      * {@link #toMap(Function, Function, BinaryOperator) toMap()},
 155      * which implements a "last wins" policy.
 156      *
 157      * @param <T> the type of input arguments to the merge function
 158      * @return a merge function which always returns its second argument
 159      * @see #firstWinsMerger()
 160      * @see #throwingMerger()
 161      */
 162     public static <T> BinaryOperator<T> lastWinsMerger() {
 163         return (u,v) -> v;
 164     }
 165 
 166     /**
 167      * Simple implementation class for {@code Collector}.
 168      *
 169      * @param <T> the type of elements to be collected
 170      * @param <R> the type of the result
 171      */
 172     private static final class CollectorImpl<T, R> implements Collector<T,R> {
 173         private final Supplier<R> resultSupplier;
 174         private final BiFunction<R, T, R> accumulator;
 175         private final BinaryOperator<R> combiner;
 176         private final Set<Characteristics> characteristics;
 177 
 178         CollectorImpl(Supplier<R> resultSupplier,
 179                       BiFunction<R, T, R> accumulator,
 180                       BinaryOperator<R> combiner,
 181                       Set<Characteristics> characteristics) {
 182             this.resultSupplier = resultSupplier;
 183             this.accumulator = accumulator;
 184             this.combiner = combiner;
 185             this.characteristics = characteristics;
 186         }
 187 
 188         CollectorImpl(Supplier<R> resultSupplier,
 189                       BiFunction<R, T, R> accumulator,
 190                       BinaryOperator<R> combiner) {
 191             this(resultSupplier, accumulator, combiner, Collections.emptySet());
 192         }
 193 
 194         @Override
 195         public BiFunction<R, T, R> accumulator() {
 196             return accumulator;
 197         }
 198 
 199         @Override
 200         public Supplier<R> resultSupplier() {
 201             return resultSupplier;
 202         }
 203 
 204         @Override
 205         public BinaryOperator<R> combiner() {
 206             return combiner;
 207         }
 208 
 209         @Override
 210         public Set<Characteristics> characteristics() {
 211             return characteristics;
 212         }
 213     }
 214 
 215     /**
 216      * Returns a {@code Collector} that accumulates the input elements into a
 217      * new {@code Collection}, in encounter order.  The {@code Collection} is
 218      * created by the provided factory.
 219      *
 220      * @param <T> the type of the input elements
 221      * @param <C> the type of the resulting {@code Collection}
 222      * @param collectionFactory a {@code Supplier} which returns a new, empty
 223      * {@code Collection} of the appropriate type
 224      * @return a {@code Collector} which collects all the input elements into a
 225      * {@code Collection}, in encounter order
 226      */
 227     public static <T, C extends Collection<T>>
 228     Collector<T, C> toCollection(Supplier<C> collectionFactory) {
 229         return new CollectorImpl<>(collectionFactory,
 230                                    (r, t) -> { r.add(t); return r; },
 231                                    (r1, r2) -> { r1.addAll(r2); return r1; },
 232                                    CH_STRICT);
 233     }
 234 
 235     /**
 236      * Returns a {@code Collector} that accumulates the input elements into a
 237      * new {@code List}. There are no guarantees on the type, mutability,
 238      * serializability, or thread-safety of the {@code List} returned.
 239      *
 240      * @param <T> the type of the input elements
 241      * @return a {@code Collector} which collects all the input elements into a
 242      * {@code List}, in encounter order
 243      */
 244     public static <T>
 245     Collector<T, List<T>> toList() {
 246         BiFunction<List<T>, T, List<T>> accumulator = (list, t) -> {
 247             switch (list.size()) {
 248                 case 0:
 249                     return Collections.singletonList(t);
 250                 case 1:
 251                     List<T> newList = new ArrayList<>();
 252                     newList.add(list.get(0));
 253                     newList.add(t);
 254                     return newList;
 255                 default:
 256                     list.add(t);
 257                     return list;
 258             }
 259         };
 260         BinaryOperator<List<T>> combiner = (left, right) -> {
 261             switch (left.size()) {
 262                 case 0:
 263                     return right;
 264                 case 1:
 265                     List<T> newList = new ArrayList<>(left.size() + right.size());
 266                     newList.addAll(left);
 267                     newList.addAll(right);
 268                     return newList;
 269                 default:
 270                     left.addAll(right);
 271                     return left;
 272             }
 273         };
 274         return new CollectorImpl<>(Collections::emptyList, accumulator, combiner);
 275     }
 276 
 277     /**
 278      * Returns a {@code Collector} that accumulates the input elements into a
 279      * new {@code Set}. There are no guarantees on the type, mutability,
 280      * serializability, or thread-safety of the {@code Set} returned.
 281      *
 282      * <p>This is an {@link Collector.Characteristics#UNORDERED unordered}
 283      * Collector.
 284      *
 285      * @param <T> the type of the input elements
 286      * @return a {@code Collector} which collects all the input elements into a
 287      * {@code Set}
 288      */
 289     public static <T>
 290     Collector<T, Set<T>> toSet() {
 291         return new CollectorImpl<>((Supplier<Set<T>>) HashSet::new,
 292                                    (r, t) -> { r.add(t); return r; },
 293                                    (r1, r2) -> { r1.addAll(r2); return r1; },
 294                                    CH_STRICT_UNORDERED);
 295     }
 296 
 297     /**
 298      * Returns a {@code Collector} that concatenates the input elements into a
 299      * new {@link StringBuilder}.
 300      *
 301      * @return a {@code Collector} which collects String elements into a
 302      * {@code StringBuilder}, in encounter order
 303      */
 304     public static Collector<String, StringBuilder> toStringBuilder() {
 305         return new CollectorImpl<>(StringBuilder::new,
 306                                    (r, t) -> { r.append(t); return r; },
 307                                    (r1, r2) -> { r1.append(r2); return r1; },
 308                                    CH_STRICT);
 309     }
 310 
 311     /**
 312      * Returns a {@code Collector} that concatenates the input elements into a
 313      * new {@link StringJoiner}, using the specified delimiter.
 314      *
 315      * @param delimiter the delimiter to be used between each element
 316      * @return A {@code Collector} which collects String elements into a
 317      * {@code StringJoiner}, in encounter order
 318      */
 319     public static Collector<CharSequence, StringJoiner> toStringJoiner(CharSequence delimiter) {
 320         BinaryOperator<StringJoiner> merger = (sj, other) -> {
 321             if (other.length() > 0)
 322                 sj.add(other.toString());
 323             return sj;
 324         };
 325         return new CollectorImpl<>(() -> new StringJoiner(delimiter),
 326                                    (r, t) -> { r.add(t); return r; },
 327                                    merger, CH_STRICT);
 328     }
 329 
 330     /**
 331      * {@code BinaryOperator<Map>} that merges the contents of its right
 332      * argument into its left argument, using the provided merge function to
 333      * handle duplicate keys.
 334      *
 335      * @param <K> type of the map keys
 336      * @param <V> type of the map values
 337      * @param <M> type of the map
 338      * @param mergeFunction A merge function suitable for
 339      * {@link Map#merge(Object, Object, BiFunction) Map.merge()}
 340      * @return a merge function for two maps
 341      */
 342     private static <K, V, M extends Map<K,V>>
 343     BinaryOperator<M> mapMerger(BinaryOperator<V> mergeFunction) {
 344         return (m1, m2) -> {
 345             for (Map.Entry<K,V> e : m2.entrySet())
 346                 m1.merge(e.getKey(), e.getValue(), mergeFunction);
 347             return m1;
 348         };
 349     }
 350 
 351     /**
 352      * Adapts a {@code Collector<U,R>} to a {@code Collector<T,R>} by applying
 353      * a mapping function to each input element before accumulation.
 354      *
 355      * @apiNote
 356      * The {@code mapping()} collectors are most useful when used in a
 357      * multi-level reduction, downstream of {@code groupingBy} or
 358      * {@code partitioningBy}.  For example, given a stream of
 359      * {@code Person}, to accumulate the set of last names in each city:
 360      * <pre>{@code
 361      *     Map<City, Set<String>> lastNamesByCity
 362      *         = people.stream().collect(groupingBy(Person::getCity,
 363      *                                              mapping(Person::getLastName, toSet())));
 364      * }</pre>
 365      *
 366      * @param <T> the type of the input elements
 367      * @param <U> type of elements accepted by downstream collector
 368      * @param <R> result type of collector
 369      * @param mapper a function to be applied to the input elements
 370      * @param downstream a collector which will accept mapped values
 371      * @return a collector which applies the mapping function to the input
 372      * elements and provides the mapped results to the downstream collector
 373      */
 374     public static <T, U, R> Collector<T, R>
 375     mapping(Function<? super T, ? extends U> mapper, Collector<? super U, R> downstream) {
 376         BiFunction<R, ? super U, R> downstreamAccumulator = downstream.accumulator();
 377         return new CollectorImpl<>(downstream.resultSupplier(),
 378                                    (r, t) -> downstreamAccumulator.apply(r, mapper.apply(t)),
 379                                    downstream.combiner(), downstream.characteristics());
 380     }
 381 
 382     /**
 383      * Returns a {@code Collector<T, Long>} that counts the number of input
 384      * elements.
 385      *
 386      * @implSpec
 387      * This produces a result equivalent to:
 388      * <pre>{@code
 389      *     reducing(0L, e -> 1L, Long::sum)
 390      * }</pre>
 391      *
 392      * @param <T> the type of the input elements
 393      * @return a {@code Collector} that counts the input elements
 394      */
 395     public static <T> Collector<T, Long>
 396     counting() {
 397         return reducing(0L, e -> 1L, Long::sum);
 398     }
 399 
 400     /**
 401      * Returns a {@code Collector<T, T>} that produces the minimal element
 402      * according to a given {@code Comparator}.
 403      *
 404      * @implSpec
 405      * This produces a result equivalent to:
 406      * <pre>{@code
 407      *     reducing(Comparators.lesserOf(comparator))
 408      * }</pre>
 409      *
 410      * @param <T> the type of the input elements
 411      * @param comparator a {@code Comparator} for comparing elements
 412      * @return a {@code Collector} that produces the minimal value
 413      */
 414     public static <T> Collector<T, T>
 415     minBy(Comparator<? super T> comparator) {
 416         return reducing(Comparators.lesserOf(comparator));
 417     }
 418 
 419     /**
 420      * Returns a {@code Collector<T, T>} that produces the maximal element
 421      * according to a given {@code Comparator}.
 422      *
 423      * @implSpec
 424      * This produces a result equivalent to:
 425      * <pre>{@code
 426      *     reducing(Comparators.greaterOf(comparator))
 427      * }</pre>
 428      *
 429      * @param <T> the type of the input elements
 430      * @param comparator a {@code Comparator} for comparing elements
 431      * @return a {@code Collector} that produces the maximal value
 432      */
 433     public static <T> Collector<T, T>
 434     maxBy(Comparator<? super T> comparator) {
 435         return reducing(Comparators.greaterOf(comparator));
 436     }
 437 
 438     /**
 439      * Returns a {@code Collector<T, Long>} that produces the sum of a
 440      * long-valued function applied to the input element.
 441      *
 442      * @implSpec
 443      * This produces a result equivalent to:
 444      * <pre>{@code
 445      *     reducing(0L, mapper, Long::sum)
 446      * }</pre>
 447      *
 448      * @param <T> the type of the input elements
 449      * @param mapper a function extracting the property to be summed
 450      * @return a {@code Collector} that produces the sum of a derived property
 451      */
 452     public static <T> Collector<T, Long>
 453     sumBy(Function<? super T, Long> mapper) {
 454         return reducing(0L, mapper, Long::sum);
 455     }
 456 
 457     /**
 458      * Returns a {@code Collector<T,T>} which performs a reduction of its
 459      * input elements under a specified {@code BinaryOperator}.
 460      *
 461      * @apiNote
 462      * The {@code reducing()} collectors are most useful when used in a
 463      * multi-level reduction, downstream of {@code groupingBy} or
 464      * {@code partitioningBy}.  To perform a simple reduction on a stream,
 465      * use {@link Stream#reduce(BinaryOperator)} instead.
 466      *
 467      * @param <T> element type for the input and output of the reduction
 468      * @param identity the identity value for the reduction (also, the value
 469      *                 that is returned when there are no input elements)
 470      * @param op a {@code BinaryOperator<T>} used to reduce the input elements
 471      * @return a {@code Collector} which implements the reduction operation
 472      *
 473      * @see #reducing(BinaryOperator)
 474      * @see #reducing(Object, Function, BinaryOperator)
 475      */
 476     public static <T> Collector<T, T>
 477     reducing(T identity, BinaryOperator<T> op) {
 478         return new CollectorImpl<>(() -> identity, (r, t) -> (r == null ? t : op.apply(r, t)), op);
 479     }
 480 
 481     /**
 482      * Returns a {@code Collector<T,T>} which performs a reduction of its
 483      * input elements under a specified {@code BinaryOperator}.
 484      *
 485      * @apiNote
 486      * The {@code reducing()} collectors are most useful when used in a
 487      * multi-level reduction, downstream of {@code groupingBy} or
 488      * {@code partitioningBy}.  To perform a simple reduction on a stream,
 489      * use {@link Stream#reduce(BinaryOperator)} instead.
 490      *
 491      * <p>For example, given a stream of {@code Person}, to calculate tallest
 492      * person in each city:
 493      * <pre>{@code
 494      *     Comparator<Person> byHeight = Comparators.comparing(Person::getHeight);
 495      *     BinaryOperator<Person> tallerOf = Comparators.greaterOf(byHeight);
 496      *     Map<City, Person> tallestByCity
 497      *         = people.stream().collect(groupingBy(Person::getCity, reducing(tallerOf)));
 498      * }</pre>
 499      *
 500      * @implSpec
 501      * The default implementation is equivalent to:
 502      * <pre>{@code
 503      *     reducing(null, op);
 504      * }</pre>
 505      *
 506      * @param <T> element type for the input and output of the reduction
 507      * @param op a {@code BinaryOperator<T>} used to reduce the input elements
 508      * @return a {@code Collector} which implements the reduction operation
 509      *
 510      * @see #reducing(Object, BinaryOperator)
 511      * @see #reducing(Object, Function, BinaryOperator)
 512      */
 513     public static <T> Collector<T, T>
 514     reducing(BinaryOperator<T> op) {
 515         return reducing(null, op);
 516     }
 517 
 518     /**
 519      * Returns a {@code Collector<T,U>} which performs a reduction of its
 520      * input elements under a specified mapping function and
 521      * {@code BinaryOperator}. This is a generalization of
 522      * {@link #reducing(Object, BinaryOperator)} which allows a transformation
 523      * of the elements before reduction.
 524      *
 525      * @apiNote
 526      * The {@code reducing()} collectors are most useful when used in a
 527      * multi-level reduction, downstream of {@code groupingBy} or
 528      * {@code partitioningBy}.  To perform a simple reduction on a stream,
 529      * use {@link Stream#reduce(BinaryOperator)} instead.
 530      *
 531      * <p>For example, given a stream of {@code Person}, to calculate the longest
 532      * last name of residents in each city:
 533      * <pre>{@code
 534      *     Comparator<String> byLength = Comparators.comparing(String::length);
 535      *     BinaryOperator<String> longerOf = Comparators.greaterOf(byLength);
 536      *     Map<City, String> longestLastNameByCity
 537      *         = people.stream().collect(groupingBy(Person::getCity,
 538      *                                              reducing(Person::getLastName, longerOf)));
 539      * }</pre>
 540      *
 541      * @param <T> the type of the input elements
 542      * @param <U> the type of the mapped values
 543      * @param identity the identity value for the reduction (also, the value
 544      *                 that is returned when there are no input elements)
 545      * @param mapper a mapping function to apply to each input value
 546      * @param op a {@code BinaryOperator<U>} used to reduce the mapped values
 547      * @return a {@code Collector} implementing the map-reduce operation
 548      *
 549      * @see #reducing(Object, BinaryOperator)
 550      * @see #reducing(BinaryOperator)
 551      */
 552     public static <T, U>
 553     Collector<T, U> reducing(U identity,
 554                              Function<? super T, ? extends U> mapper,
 555                              BinaryOperator<U> op) {
 556         return new CollectorImpl<>(() -> identity,
 557                                    (r, t) -> (r == null ? mapper.apply(t) : op.apply(r, mapper.apply(t))),
 558                                    op);
 559     }
 560 
 561     /**
 562      * Returns a {@code Collector} implementing a "group by" operation on
 563      * input elements of type {@code T}, grouping elements according to a
 564      * classification function.
 565      *
 566      * <p>The classification function maps elements to some key type {@code K}.
 567      * The collector produces a {@code Map<K, List<T>>} whose keys are the
 568      * values resulting from applying the classification function to the input
 569      * elements, and whose corresponding values are {@code List}s containing the
 570      * input elements which map to the associated key under the classification
 571      * function.
 572      *
 573      * <p>There are no guarantees on the type, mutability, serializability, or
 574      * thread-safety of the {@code Map} or {@code List} objects returned.
 575      * @implSpec
 576      * This produces a result similar to:
 577      * <pre>{@code
 578      *     groupingBy(classifier, toList());
 579      * }</pre>
 580      *
 581      * @param <T> the type of the input elements
 582      * @param <K> the type of the keys
 583      * @param classifier the classifier function mapping input elements to keys
 584      * @return a {@code Collector} implementing the group-by operation
 585      *
 586      * @see #groupingBy(Function, Collector)
 587      * @see #groupingBy(Function, Supplier, Collector)
 588      * @see #groupingByConcurrent(Function)
 589      */
 590     public static <T, K>
 591     Collector<T, Map<K, List<T>>> groupingBy(Function<? super T, ? extends K> classifier) {
 592         return groupingBy(classifier, HashMap::new, toList());
 593     }
 594 
 595     /**
 596      * Returns a {@code Collector} implementing a cascaded "group by" operation
 597      * on input elements of type {@code T}, grouping elements according to a
 598      * classification function, and then performing a reduction operation on
 599      * the values associated with a given key using the specified downstream
 600      * {@code Collector}.
 601      *
 602      * <p>The classification function maps elements to some key type {@code K}.
 603      * The downstream collector operates on elements of type {@code T} and
 604      * produces a result of type {@code D}. The resulting collector produces a
 605      * {@code Map<K, D>}.
 606      *
 607      * <p>There are no guarantees on the type, mutability,
 608      * serializability, or thread-safety of the {@code Map} returned.
 609      *
 610      * <p>For example, to compute the set of last names of people in each city:
 611      * <pre>{@code
 612      *     Map<City, Set<String>> namesByCity
 613      *         = people.stream().collect(groupingBy(Person::getCity,
 614      *                                              mapping(Person::getLastName, toSet())));
 615      * }</pre>
 616      *
 617      * @param <T> the type of the input elements
 618      * @param <K> the type of the keys
 619      * @param <D> the result type of the downstream reduction
 620      * @param classifier a classifier function mapping input elements to keys
 621      * @param downstream a {@code Collector} implementing the downstream reduction
 622      * @return a {@code Collector} implementing the cascaded group-by operation
 623      * @see #groupingBy(Function)
 624      *
 625      * @see #groupingBy(Function, Supplier, Collector)
 626      * @see #groupingByConcurrent(Function, Collector)
 627      */
 628     public static <T, K, D>
 629     Collector<T, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,
 630                                        Collector<? super T, D> downstream) {
 631         return groupingBy(classifier, HashMap::new, downstream);
 632     }
 633 
 634     /**
 635      * Returns a {@code Collector} implementing a cascaded "group by" operation
 636      * on input elements of type {@code T}, grouping elements according to a
 637      * classification function, and then performing a reduction operation on
 638      * the values associated with a given key using the specified downstream
 639      * {@code Collector}.  The {@code Map} produced by the Collector is created
 640      * with the supplied factory function.
 641      *
 642      * <p>The classification function maps elements to some key type {@code K}.
 643      * The downstream collector operates on elements of type {@code T} and
 644      * produces a result of type {@code D}. The resulting collector produces a
 645      * {@code Map<K, D>}.
 646      *
 647      * <p>For example, to compute the set of last names of people in each city,
 648      * where the city names are sorted:
 649      * <pre>{@code
 650      *     Map<City, Set<String>> namesByCity
 651      *         = people.stream().collect(groupingBy(Person::getCity, TreeMap::new,
 652      *                                              mapping(Person::getLastName, toSet())));
 653      * }</pre>
 654      *
 655      * @param <T> the type of the input elements
 656      * @param <K> the type of the keys
 657      * @param <D> the result type of the downstream reduction
 658      * @param <M> the type of the resulting {@code Map}
 659      * @param classifier a classifier function mapping input elements to keys
 660      * @param downstream a {@code Collector} implementing the downstream reduction
 661      * @param mapFactory a function which, when called, produces a new empty
 662      *                   {@code Map} of the desired type
 663      * @return a {@code Collector} implementing the cascaded group-by operation
 664      *
 665      * @see #groupingBy(Function, Collector)
 666      * @see #groupingBy(Function)
 667      * @see #groupingByConcurrent(Function, Supplier, Collector)
 668      */
 669     public static <T, K, D, M extends Map<K, D>>
 670     Collector<T, M> groupingBy(Function<? super T, ? extends K> classifier,
 671                                Supplier<M> mapFactory,
 672                                Collector<? super T, D> downstream) {
 673         Supplier<D> downstreamSupplier = downstream.resultSupplier();
 674         BiFunction<D, ? super T, D> downstreamAccumulator = downstream.accumulator();
 675         BiFunction<M, T, M> accumulator = (m, t) -> {
 676             K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key");
 677             D oldContainer = m.computeIfAbsent(key, k -> downstreamSupplier.get());
 678             D newContainer = downstreamAccumulator.apply(oldContainer, t);
 679             if (newContainer != oldContainer)
 680                 m.put(key, newContainer);
 681             return m;
 682         };
 683         return new CollectorImpl<>(mapFactory, accumulator, mapMerger(downstream.combiner()), CH_STRICT);
 684     }
 685 
 686     /**
 687      * Returns a {@code Collector} implementing a concurrent "group by"
 688      * operation on input elements of type {@code T}, grouping elements
 689      * according to a classification function.
 690      *
 691      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
 692      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
 693      *
 694      * <p>The classification function maps elements to some key type {@code K}.
 695      * The collector produces a {@code ConcurrentMap<K, List<T>>} whose keys are the
 696      * values resulting from applying the classification function to the input
 697      * elements, and whose corresponding values are {@code List}s containing the
 698      * input elements which map to the associated key under the classification
 699      * function.
 700      *
 701      * <p>There are no guarantees on the type, mutability, or serializability
 702      * of the {@code Map} or {@code List} objects returned, or of the
 703      * thread-safety of the {@code List} objects returned.
 704      * @implSpec
 705      * This produces a result similar to:
 706      * <pre>{@code
 707      *     groupingByConcurrent(classifier, toList());
 708      * }</pre>
 709      *
 710      * @param <T> the type of the input elements
 711      * @param <K> the type of the keys
 712      * @param classifier a classifier function mapping input elements to keys
 713      * @return a {@code Collector} implementing the group-by operation
 714      *
 715      * @see #groupingBy(Function)
 716      * @see #groupingByConcurrent(Function, Collector)
 717      * @see #groupingByConcurrent(Function, Supplier, Collector)
 718      */
 719     public static <T, K>
 720     Collector<T, ConcurrentMap<K, List<T>>> groupingByConcurrent(Function<? super T, ? extends K> classifier) {
 721         return groupingByConcurrent(classifier, ConcurrentHashMap::new, toList());
 722     }
 723 
 724     /**
 725      * Returns a {@code Collector} implementing a concurrent cascaded "group by"
 726      * operation on input elements of type {@code T}, grouping elements
 727      * according to a classification function, and then performing a reduction
 728      * operation on the values associated with a given key using the specified
 729      * downstream {@code Collector}.
 730      *
 731      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
 732      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
 733      *
 734      * <p>The classification function maps elements to some key type {@code K}.
 735      * The downstream collector operates on elements of type {@code T} and
 736      * produces a result of type {@code D}. The resulting collector produces a
 737      * {@code Map<K, D>}.
 738      *
 739      * <p>For example, to compute the set of last names of people in each city,
 740      * where the city names are sorted:
 741      * <pre>{@code
 742      *     ConcurrentMap<City, Set<String>> namesByCity
 743      *         = people.stream().collect(groupingByConcurrent(Person::getCity, TreeMap::new,
 744      *                                                        mapping(Person::getLastName, toSet())));
 745      * }</pre>
 746      *
 747      * @param <T> the type of the input elements
 748      * @param <K> the type of the keys
 749      * @param <D> the result type of the downstream reduction
 750      * @param classifier a classifier function mapping input elements to keys
 751      * @param downstream a {@code Collector} implementing the downstream reduction
 752      * @return a {@code Collector} implementing the cascaded group-by operation
 753      *
 754      * @see #groupingBy(Function, Collector)
 755      * @see #groupingByConcurrent(Function)
 756      * @see #groupingByConcurrent(Function, Supplier, Collector)
 757      */
 758     public static <T, K, D>
 759     Collector<T, ConcurrentMap<K, D>> groupingByConcurrent(Function<? super T, ? extends K> classifier,
 760                                                            Collector<? super T, D> downstream) {
 761         return groupingByConcurrent(classifier, ConcurrentHashMap::new, downstream);
 762     }
 763 
 764     /**
 765      * Returns a concurrent {@code Collector} implementing a cascaded "group by"
 766      * operation on input elements of type {@code T}, grouping elements
 767      * according to a classification function, and then performing a reduction
 768      * operation on the values associated with a given key using the specified
 769      * downstream {@code Collector}.  The {@code ConcurrentMap} produced by the
 770      * Collector is created with the supplied factory function.
 771      *
 772      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
 773      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
 774      *
 775      * <p>The classification function maps elements to some key type {@code K}.
 776      * The downstream collector operates on elements of type {@code T} and
 777      * produces a result of type {@code D}. The resulting collector produces a
 778      * {@code Map<K, D>}.
 779      *
 780      * <p>For example, to compute the set of last names of people in each city,
 781      * where the city names are sorted:
 782      * <pre>{@code
 783      *     ConcurrentMap<City, Set<String>> namesByCity
 784      *         = people.stream().collect(groupingBy(Person::getCity, ConcurrentSkipListMap::new,
 785      *                                              mapping(Person::getLastName, toSet())));
 786      * }</pre>
 787      *
 788      *
 789      * @param <T> the type of the input elements
 790      * @param <K> the type of the keys
 791      * @param <D> the result type of the downstream reduction
 792      * @param <M> the type of the resulting {@code ConcurrentMap}
 793      * @param classifier a classifier function mapping input elements to keys
 794      * @param downstream a {@code Collector} implementing the downstream reduction
 795      * @param mapFactory a function which, when called, produces a new empty
 796      *                   {@code ConcurrentMap} of the desired type
 797      * @return a {@code Collector} implementing the cascaded group-by operation
 798      *
 799      * @see #groupingByConcurrent(Function)
 800      * @see #groupingByConcurrent(Function, Collector)
 801      * @see #groupingBy(Function, Supplier, Collector)
 802      */
 803     public static <T, K, D, M extends ConcurrentMap<K, D>>
 804     Collector<T, M> groupingByConcurrent(Function<? super T, ? extends K> classifier,
 805                                          Supplier<M> mapFactory,
 806                                          Collector<? super T, D> downstream) {
 807         Supplier<D> downstreamSupplier = downstream.resultSupplier();
 808         BiFunction<D, ? super T, D> downstreamAccumulator = downstream.accumulator();
 809         BinaryOperator<M> combiner = mapMerger(downstream.combiner());
 810         if (downstream.characteristics().contains(Collector.Characteristics.CONCURRENT)) {
 811             BiFunction<M, T, M> accumulator = (m, t) -> {
 812                 K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key");
 813                 downstreamAccumulator.apply(m.computeIfAbsent(key, k -> downstreamSupplier.get()), t);
 814                 return m;
 815             };
 816             return new CollectorImpl<>(mapFactory, accumulator, combiner, CH_CONCURRENT);
 817         } else if (downstream.characteristics().contains(Collector.Characteristics.STRICTLY_MUTATIVE)) {
 818             BiFunction<M, T, M> accumulator = (m, t) -> {
 819                 K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key");
 820                 D resultContainer = m.computeIfAbsent(key, k -> downstreamSupplier.get());
 821                 synchronized (resultContainer) {
 822                     downstreamAccumulator.apply(resultContainer, t);
 823                 }
 824                 return m;
 825             };
 826             return new CollectorImpl<>(mapFactory, accumulator, combiner, CH_CONCURRENT);
 827         } else {
 828             BiFunction<M, T, M> accumulator = (m, t) -> {
 829                 K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key");
 830                 do {
 831                     D oldResult = m.computeIfAbsent(key, k -> downstreamSupplier.get());
 832                     if (oldResult == null) {
 833                         if (m.putIfAbsent(key, downstreamAccumulator.apply(null, t)) == null)
 834                             return m;
 835                     } else {
 836                         synchronized (oldResult) {
 837                             if (m.get(key) != oldResult)
 838                                 continue;
 839                             D newResult = downstreamAccumulator.apply(oldResult, t);
 840                             if (oldResult != newResult)
 841                                 m.put(key, newResult);
 842                             return m;
 843                         }
 844                     }
 845                 } while (true);
 846             };
 847             return new CollectorImpl<>(mapFactory, accumulator, combiner, CH_CONCURRENT);
 848         }
 849     }
 850 
 851     /**
 852      * Returns a {@code Collector} which partitions the input elements according
 853      * to a {@code Predicate}, and organizes them into a
 854      * {@code Map<Boolean, List<T>>}.
 855      *
 856      * There are no guarantees on the type, mutability,
 857      * serializability, or thread-safety of the {@code Map} returned.
 858      *
 859      * @param <T> the type of the input elements
 860      * @param predicate a predicate used for classifying input elements
 861      * @return a {@code Collector} implementing the partitioning operation
 862      *
 863      * @see #partitioningBy(Predicate, Collector)
 864      */
 865     public static <T>
 866     Collector<T, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate) {
 867         return partitioningBy(predicate, toList());
 868     }
 869 
 870     /**
 871      * Returns a {@code Collector} which partitions the input elements according
 872      * to a {@code Predicate}, reduces the values in each partition according to
 873      * another {@code Collector}, and organizes them into a
 874      * {@code Map<Boolean, D>} whose values are the result of the downstream
 875      * reduction.
 876      *
 877      * <p>There are no guarantees on the type, mutability,
 878      * serializability, or thread-safety of the {@code Map} returned.
 879      *
 880      * @param <T> the type of the input elements
 881      * @param <D> the result type of the downstream reduction
 882      * @param predicate a predicate used for classifying input elements
 883      * @param downstream a {@code Collector} implementing the downstream
 884      *                   reduction
 885      * @return a {@code Collector} implementing the cascaded partitioning
 886      *         operation
 887      *
 888      * @see #partitioningBy(Predicate)
 889      */
 890     public static <T, D>
 891     Collector<T, Map<Boolean, D>> partitioningBy(Predicate<? super T> predicate,
 892                                                  Collector<? super T, D> downstream) {
 893         BiFunction<D, ? super T, D> downstreamAccumulator = downstream.accumulator();
 894         BiFunction<Map<Boolean, D>, T, Map<Boolean, D>> accumulator = (result, t) -> {
 895             Partition<D> asPartition = ((Partition<D>) result);
 896             if (predicate.test(t)) {
 897                 D newResult = downstreamAccumulator.apply(asPartition.forTrue, t);
 898                 if (newResult != asPartition.forTrue)
 899                     asPartition.forTrue = newResult;
 900             } else {
 901                 D newResult = downstreamAccumulator.apply(asPartition.forFalse, t);
 902                 if (newResult != asPartition.forFalse)
 903                     asPartition.forFalse = newResult;
 904             }
 905             return result;
 906         };
 907         return new CollectorImpl<>(() -> new Partition<>(downstream.resultSupplier().get(),
 908                                                          downstream.resultSupplier().get()),
 909                                    accumulator, partitionMerger(downstream.combiner()), CH_STRICT);
 910     }
 911 
 912     /**
 913      * Merge function for two partitions, given a merge function for the
 914      * elements.
 915      */
 916     private static <D> BinaryOperator<Map<Boolean, D>> partitionMerger(BinaryOperator<D> op) {
 917         return (m1, m2) -> {
 918             Partition<D> left = (Partition<D>) m1;
 919             Partition<D> right = (Partition<D>) m2;
 920             if (left.forFalse == null)
 921                 left.forFalse = right.forFalse;
 922             else if (right.forFalse != null)
 923                 left.forFalse = op.apply(left.forFalse, right.forFalse);
 924             if (left.forTrue == null)
 925                 left.forTrue = right.forTrue;
 926             else if (right.forTrue != null)
 927                 left.forTrue = op.apply(left.forTrue, right.forTrue);
 928             return left;
 929         };
 930     }
 931 
 932     /**
 933      * Accumulate elements into a {@code Map} whose keys and values are the
 934      * result of applying mapping functions to the input elements.
 935      * If the mapped keys contains duplicates (according to
 936      * {@link Object#equals(Object)}), an {@code IllegalStateException} is
 937      * thrown when the collection operation is performed.  If the mapped keys
 938      * may have duplicates, use {@link #toMap(Function, Function, BinaryOperator)}
 939      * instead.
 940      *
 941      * @apiNote
 942      * It is common for either the key or the value to be the input elements.
 943      * In this case, the utility method
 944      * {@link java.util.function.Function#identity()} may be helpful.
 945      * For example, the following produces a {@code Map} mapping
 946      * students to their grade point average:
 947      * <pre>{@code
 948      *     Map<Student, Double> studentToGPA
 949      *         students.stream().collect(toMap(Functions.identity(),
 950      *                                         student -> computeGPA(student)));
 951      * }</pre>
 952      * And the following produces a {@code Map} mapping a unique identifier to
 953      * students:
 954      * <pre>{@code
 955      *     Map<String, Student> studentIdToStudent
 956      *         students.stream().collect(toMap(Student::getId,
 957      *                                         Functions.identity());
 958      * }</pre>
 959      *
 960      * @param <T> the type of the input elements
 961      * @param <K> the output type of the key mapping function
 962      * @param <U> the output type of the value mapping function
 963      * @param keyMapper a mapping function to produce keys
 964      * @param valueMapper a mapping function to produce values
 965      * @return a {@code Collector} which collects elements into a {@code Map}
 966      * whose keys and values are the result of applying mapping functions to
 967      * the input elements
 968      *
 969      * @see #toMap(Function, Function, BinaryOperator)
 970      * @see #toMap(Function, Function, BinaryOperator, Supplier)
 971      * @see #toConcurrentMap(Function, Function)
 972      */
 973     public static <T, K, U>
 974     Collector<T, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
 975                                  Function<? super T, ? extends U> valueMapper) {
 976         return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
 977     }
 978 
 979     /**
 980      * Accumulate elements into a {@code Map} whose keys and values are the
 981      * result of applying mapping functions to the input elements. If the mapped
 982      * keys contains duplicates (according to {@link Object#equals(Object)}),
 983      * the value mapping function is applied to each equal element, and the
 984      * results are merged using the provided merging function.
 985      *
 986      * @apiNote
 987      * There are multiple ways to deal with collisions between multiple elements
 988      * mapping to the same key.  There are some predefined merging functions,
 989      * such as {@link #throwingMerger()}, {@link #firstWinsMerger()}, and
 990      * {@link #lastWinsMerger()}, that implement common policies, or you can
 991      * implement custom policies easily.  For example, if you have a stream
 992      * of {@code Person}, and you want to produce a "phone book" mapping name to
 993      * address, but it is possible that two persons have the same name, you can
 994      * do as follows to gracefully deals with these collisions, and produce a
 995      * {@code Map} mapping names to a concatenated list of addresses:
 996      * <pre>{@code
 997      *     Map<String, String> phoneBook
 998      *         people.stream().collect(toMap(Person::getName,
 999      *                                       Person::getAddress,
1000      *                                       (s, a) -> s + ", " + a));
1001      * }</pre>
1002      *
1003      * @param <T> the type of the input elements
1004      * @param <K> the output type of the key mapping function
1005      * @param <U> the output type of the value mapping function
1006      * @param keyMapper a mapping function to produce keys
1007      * @param valueMapper a mapping function to produce values
1008      * @param mergeFunction a merge function, used to resolve collisions between
1009      *                      values associated with the same key, as supplied
1010      *                      to {@link Map#merge(Object, Object, BiFunction)}
1011      * @return a {@code Collector} which collects elements into a {@code Map}
1012      * whose keys are the result of applying a key mapping function to the input
1013      * elements, and whose values are the result of applying a value mapping
1014      * function to all input elements equal to the key and combining them
1015      * using the merge function
1016      *
1017      * @see #toMap(Function, Function)
1018      * @see #toMap(Function, Function, BinaryOperator, Supplier)
1019      * @see #toConcurrentMap(Function, Function, BinaryOperator)
1020      */
1021     public static <T, K, U>
1022     Collector<T, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
1023                                  Function<? super T, ? extends U> valueMapper,
1024                                  BinaryOperator<U> mergeFunction) {
1025         return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
1026     }
1027 
1028     /**
1029      * Accumulate elements into a {@code Map} whose keys and values are the
1030      * result of applying mapping functions to the input elements. If the mapped
1031      * keys contains duplicates (according to {@link Object#equals(Object)}),
1032      * the value mapping function is applied to each equal element, and the
1033      * results are merged using the provided merging function.  The {@code Map}
1034      * is created by a provided supplier function.
1035      *
1036      * @param <T> the type of the input elements
1037      * @param <K> the output type of the key mapping function
1038      * @param <U> the output type of the value mapping function
1039      * @param <M> the type of the resulting {@code Map}
1040      * @param keyMapper a mapping function to produce keys
1041      * @param valueMapper a mapping function to produce values
1042      * @param mergeFunction a merge function, used to resolve collisions between
1043      *                      values associated with the same key, as supplied
1044      *                      to {@link Map#merge(Object, Object, BiFunction)}
1045      * @param mapSupplier a function which returns a new, empty {@code Map} into
1046      *                    which the results will be inserted
1047      * @return a {@code Collector} which collects elements into a {@code Map}
1048      * whose keys are the result of applying a key mapping function to the input
1049      * elements, and whose values are the result of applying a value mapping
1050      * function to all input elements equal to the key and combining them
1051      * using the merge function
1052      *
1053      * @see #toMap(Function, Function)
1054      * @see #toMap(Function, Function, BinaryOperator)
1055      * @see #toConcurrentMap(Function, Function, BinaryOperator, Supplier)
1056      */
1057     public static <T, K, U, M extends Map<K, U>>
1058     Collector<T, M> toMap(Function<? super T, ? extends K> keyMapper,
1059                           Function<? super T, ? extends U> valueMapper,
1060                           BinaryOperator<U> mergeFunction,
1061                           Supplier<M> mapSupplier) {
1062         BiFunction<M, T, M> accumulator
1063                 = (map, element) -> {
1064                       map.merge(keyMapper.apply(element), valueMapper.apply(element), mergeFunction);
1065                       return map;
1066                   };
1067         return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_STRICT);
1068     }
1069 
1070     /**
1071      * Accumulate elements into a {@code ConcurrentMap} whose keys and values
1072      * are the result of applying mapping functions to the input elements.
1073      * If the mapped keys contains duplicates (according to
1074      * {@link Object#equals(Object)}), an {@code IllegalStateException} is
1075      * thrown when the collection operation is performed.  If the mapped keys
1076      * may have duplicates, use
1077      * {@link #toConcurrentMap(Function, Function, BinaryOperator)} instead.
1078      *
1079      * @apiNote
1080      * It is common for either the key or the value to be the input elements.
1081      * In this case, the utility method
1082      * {@link java.util.function.Function#identity()} may be helpful.
1083      * For example, the following produces a {@code Map} mapping
1084      * students to their grade point average:
1085      * <pre>{@code
1086      *     Map<Student, Double> studentToGPA
1087      *         students.stream().collect(toMap(Functions.identity(),
1088      *                                         student -> computeGPA(student)));
1089      * }</pre>
1090      * And the following produces a {@code Map} mapping a unique identifier to
1091      * students:
1092      * <pre>{@code
1093      *     Map<String, Student> studentIdToStudent
1094      *         students.stream().collect(toConcurrentMap(Student::getId,
1095      *                                                   Functions.identity());
1096      * }</pre>
1097      *
1098      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
1099      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
1100      *
1101      * @param <T> the type of the input elements
1102      * @param <K> the output type of the key mapping function
1103      * @param <U> the output type of the value mapping function
1104      * @param keyMapper the mapping function to produce keys
1105      * @param valueMapper the mapping function to produce values
1106      * @return a concurrent {@code Collector} which collects elements into a
1107      * {@code ConcurrentMap} whose keys are the result of applying a key mapping
1108      * function to the input elements, and whose values are the result of
1109      * applying a value mapping function to the input elements
1110      *
1111      * @see #toMap(Function, Function)
1112      * @see #toConcurrentMap(Function, Function, BinaryOperator)
1113      * @see #toConcurrentMap(Function, Function, BinaryOperator, Supplier)
1114      */
1115     public static <T, K, U>
1116     Collector<T, ConcurrentMap<K,U>> toConcurrentMap(Function<? super T, ? extends K> keyMapper,
1117                                                      Function<? super T, ? extends U> valueMapper) {
1118         return toConcurrentMap(keyMapper, valueMapper, throwingMerger(), ConcurrentHashMap::new);
1119     }
1120 
1121     /**
1122      * Accumulate elements into a {@code ConcurrentMap} whose keys and values
1123      * are the result of applying mapping functions to the input elements. If
1124      * the mapped keys contains duplicates (according to {@link Object#equals(Object)}),
1125      * the value mapping function is applied to each equal element, and the
1126      * results are merged using the provided merging function.
1127      *
1128      * @apiNote
1129      * There are multiple ways to deal with collisions between multiple elements
1130      * mapping to the same key.  There are some predefined merging functions,
1131      * such as {@link #throwingMerger()}, {@link #firstWinsMerger()}, and
1132      * {@link #lastWinsMerger()}, that implement common policies, or you can
1133      * implement custom policies easily.  For example, if you have a stream
1134      * of {@code Person}, and you want to produce a "phone book" mapping name to
1135      * address, but it is possible that two persons have the same name, you can
1136      * do as follows to gracefully deals with these collisions, and produce a
1137      * {@code Map} mapping names to a concatenated list of addresses:
1138      * <pre>{@code
1139      *     Map<String, String> phoneBook
1140      *         people.stream().collect(toConcurrentMap(Person::getName,
1141      *                                                 Person::getAddress,
1142      *                                                 (s, a) -> s + ", " + a));
1143      * }</pre>
1144      *
1145      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
1146      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
1147      *
1148      * @param <T> the type of the input elements
1149      * @param <K> the output type of the key mapping function
1150      * @param <U> the output type of the value mapping function
1151      * @param keyMapper a mapping function to produce keys
1152      * @param valueMapper a mapping function to produce values
1153      * @param mergeFunction a merge function, used to resolve collisions between
1154      *                      values associated with the same key, as supplied
1155      *                      to {@link Map#merge(Object, Object, BiFunction)}
1156      * @return a concurrent {@code Collector} which collects elements into a
1157      * {@code ConcurrentMap} whose keys are the result of applying a key mapping
1158      * function to the input elements, and whose values are the result of
1159      * applying a value mapping function to all input elements equal to the key
1160      * and combining them using the merge function
1161      *
1162      * @see #toConcurrentMap(Function, Function)
1163      * @see #toConcurrentMap(Function, Function, BinaryOperator, Supplier)
1164      * @see #toMap(Function, Function, BinaryOperator)
1165      */
1166     public static <T, K, U>
1167     Collector<T, ConcurrentMap<K,U>> toConcurrentMap(Function<? super T, ? extends K> keyMapper,
1168                                                      Function<? super T, ? extends U> valueMapper,
1169                                                      BinaryOperator<U> mergeFunction) {
1170         return toConcurrentMap(keyMapper, valueMapper, mergeFunction, ConcurrentHashMap::new);
1171     }
1172 
1173     /**
1174      * Accumulate elements into a {@code ConcurrentMap} whose keys and values
1175      * are the result of applying mapping functions to the input elements. If
1176      * the mapped keys contains duplicates (according to {@link Object#equals(Object)}),
1177      * the value mapping function is applied to each equal element, and the
1178      * results are merged using the provided merging function.  The
1179      * {@code ConcurrentMap} is created by a provided supplier function.
1180      *
1181      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
1182      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
1183      *
1184      * @param <T> the type of the input elements
1185      * @param <K> the output type of the key mapping function
1186      * @param <U> the output type of the value mapping function
1187      * @param <M> the type of the resulting {@code ConcurrentMap}
1188      * @param keyMapper a mapping function to produce keys
1189      * @param valueMapper a mapping function to produce values
1190      * @param mergeFunction a merge function, used to resolve collisions between
1191      *                      values associated with the same key, as supplied
1192      *                      to {@link Map#merge(Object, Object, BiFunction)}
1193      * @param mapSupplier a function which returns a new, empty {@code Map} into
1194      *                    which the results will be inserted
1195      * @return a concurrent {@code Collector} which collects elements into a
1196      * {@code ConcurrentMap} whose keys are the result of applying a key mapping
1197      * function to the input elements, and whose values are the result of
1198      * applying a value mapping function to all input elements equal to the key
1199      * and combining them using the merge function
1200      *
1201      * @see #toConcurrentMap(Function, Function)
1202      * @see #toConcurrentMap(Function, Function, BinaryOperator)
1203      * @see #toMap(Function, Function, BinaryOperator, Supplier)
1204      */
1205     public static <T, K, U, M extends ConcurrentMap<K, U>>
1206     Collector<T, M> toConcurrentMap(Function<? super T, ? extends K> keyMapper,
1207                                     Function<? super T, ? extends U> valueMapper,
1208                                     BinaryOperator<U> mergeFunction,
1209                                     Supplier<M> mapSupplier) {
1210         BiFunction<M, T, M> accumulator = (map, element) -> {
1211             map.merge(keyMapper.apply(element), valueMapper.apply(element), mergeFunction);
1212             return map;
1213         };
1214         return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_CONCURRENT);
1215     }
1216 
1217     /**
1218      * Returns a {@code Collector} which applies an {@code int}-producing
1219      * mapping function to each input element, and returns summary statistics
1220      * for the resulting values.
1221      *
1222      * @param <T> the type of the input elements
1223      * @param mapper a mapping function to apply to each element
1224      * @return a {@code Collector} implementing the summary-statistics reduction
1225      *
1226      * @see #toDoubleSummaryStatistics(ToDoubleFunction)
1227      * @see #toLongSummaryStatistics(ToLongFunction)
1228      */
1229     public static <T>
1230     Collector<T, IntSummaryStatistics> toIntSummaryStatistics(ToIntFunction<? super T> mapper) {
1231         return new CollectorImpl<>(IntSummaryStatistics::new,
1232                                    (r, t) -> { r.accept(mapper.applyAsInt(t)); return r; },
1233                                    (l, r) -> { l.combine(r); return l; }, CH_STRICT);
1234     }
1235 
1236     /**
1237      * Returns a {@code Collector} which applies an {@code long}-producing
1238      * mapping function to each input element, and returns summary statistics
1239      * for the resulting values.
1240      *
1241      * @param <T> the type of the input elements
1242      * @param mapper the mapping function to apply to each element
1243      * @return a {@code Collector} implementing the summary-statistics reduction
1244      *
1245      * @see #toDoubleSummaryStatistics(ToDoubleFunction)
1246      * @see #toIntSummaryStatistics(ToIntFunction)
1247      */
1248     public static <T>
1249     Collector<T, LongSummaryStatistics> toLongSummaryStatistics(ToLongFunction<? super T> mapper) {
1250         return new CollectorImpl<>(LongSummaryStatistics::new,
1251                                    (r, t) -> { r.accept(mapper.applyAsLong(t)); return r; },
1252                                    (l, r) -> { l.combine(r); return l; }, CH_STRICT);
1253     }
1254 
1255     /**
1256      * Returns a {@code Collector} which applies an {@code double}-producing
1257      * mapping function to each input element, and returns summary statistics
1258      * for the resulting values.
1259      *
1260      * @param <T> the type of the input elements
1261      * @param mapper a mapping function to apply to each element
1262      * @return a {@code Collector} implementing the summary-statistics reduction
1263      *
1264      * @see #toLongSummaryStatistics(ToLongFunction)
1265      * @see #toIntSummaryStatistics(ToIntFunction)
1266      */
1267     public static <T>
1268     Collector<T, DoubleSummaryStatistics> toDoubleSummaryStatistics(ToDoubleFunction<? super T> mapper) {
1269         return new CollectorImpl<>(DoubleSummaryStatistics::new,
1270                                    (r, t) -> { r.accept(mapper.applyAsDouble(t)); return r; },
1271                                    (l, r) -> { l.combine(r); return l; }, CH_STRICT);
1272     }
1273 
1274     /**
1275      * Implementation class used by partitioningBy.
1276      */
1277     private static final class Partition<T>
1278             extends AbstractMap<Boolean, T>
1279             implements Map<Boolean, T> {
1280         T forTrue;
1281         T forFalse;
1282 
1283         Partition(T forTrue, T forFalse) {
1284             this.forTrue = forTrue;
1285             this.forFalse = forFalse;
1286         }
1287 
1288         @Override
1289         public Set<Map.Entry<Boolean, T>> entrySet() {
1290             return new AbstractSet<Map.Entry<Boolean, T>>() {
1291                 @Override
1292                 public Iterator<Map.Entry<Boolean, T>> iterator() {
1293 
1294                     return new Iterator<Map.Entry<Boolean, T>>() {
1295                         int state = 0;
1296 
1297                         @Override
1298                         public boolean hasNext() {
1299                             return state < 2;
1300                         }
1301 
1302                         @Override
1303                         public Map.Entry<Boolean, T> next() {
1304                             if (state >= 2)
1305                                 throw new NoSuchElementException();
1306                             return (state++ == 0)
1307                                    ? new SimpleImmutableEntry<>(false, forFalse)
1308                                    : new SimpleImmutableEntry<>(true, forTrue);
1309                         }
1310                     };
1311                 }
1312 
1313                 @Override
1314                 public int size() {
1315                     return 2;
1316                 }
1317             };
1318         }
1319     }
1320 }