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 ConcurrentMap} 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>There are no guarantees on the type, mutability, or serializability
1032      * of the {@code ConcurrentMap} returned.
1033      *
1034      * <p>For example, to compute the set of last names of people in each city,
1035      * where the city names are sorted:
1036      * <pre>{@code
1037      *     ConcurrentMap<City, Set<String>> namesByCity
1038      *         = people.stream().collect(groupingByConcurrent(Person::getCity,
1039      *                                                        mapping(Person::getLastName, toSet())));
1040      * }</pre>
1041      *
1042      * @param <T> the type of the input elements
1043      * @param <K> the type of the keys
1044      * @param <A> the intermediate accumulation type of the downstream collector
1045      * @param <D> the result type of the downstream reduction
1046      * @param classifier a classifier function mapping input elements to keys
1047      * @param downstream a {@code Collector} implementing the downstream reduction
1048      * @return a concurrent, unordered {@code Collector} implementing the cascaded group-by operation
1049      *
1050      * @see #groupingBy(Function, Collector)
1051      * @see #groupingByConcurrent(Function)
1052      * @see #groupingByConcurrent(Function, Supplier, Collector)
1053      */
1054     public static <T, K, A, D>
1055     Collector<T, ?, ConcurrentMap<K, D>> groupingByConcurrent(Function<? super T, ? extends K> classifier,
1056                                                               Collector<? super T, A, D> downstream) {
1057         return groupingByConcurrent(classifier, ConcurrentHashMap::new, downstream);
1058     }
1059 
1060     /**
1061      * Returns a concurrent {@code Collector} implementing a cascaded "group by"
1062      * operation on input elements of type {@code T}, grouping elements
1063      * according to a classification function, and then performing a reduction
1064      * operation on the values associated with a given key using the specified
1065      * downstream {@code Collector}.  The {@code ConcurrentMap} produced by the
1066      * Collector is created with the supplied factory function.
1067      *
1068      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
1069      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
1070      *
1071      * <p>The classification function maps elements to some key type {@code K}.
1072      * The downstream collector operates on elements of type {@code T} and
1073      * produces a result of type {@code D}. The resulting collector produces a
1074      * {@code Map<K, D>}.
1075      *
1076      * <p>For example, to compute the set of last names of people in each city,
1077      * where the city names are sorted:
1078      * <pre>{@code
1079      *     ConcurrentMap<City, Set<String>> namesByCity
1080      *         = people.stream().collect(groupingBy(Person::getCity, ConcurrentSkipListMap::new,
1081      *                                              mapping(Person::getLastName, toSet())));
1082      * }</pre>
1083      *
1084      *
1085      * @param <T> the type of the input elements
1086      * @param <K> the type of the keys
1087      * @param <A> the intermediate accumulation type of the downstream collector
1088      * @param <D> the result type of the downstream reduction
1089      * @param <M> the type of the resulting {@code ConcurrentMap}
1090      * @param classifier a classifier function mapping input elements to keys
1091      * @param downstream a {@code Collector} implementing the downstream reduction
1092      * @param mapFactory a function which, when called, produces a new empty
1093      *                   {@code ConcurrentMap} of the desired type
1094      * @return a concurrent, unordered {@code Collector} implementing the cascaded group-by operation
1095      *
1096      * @see #groupingByConcurrent(Function)
1097      * @see #groupingByConcurrent(Function, Collector)
1098      * @see #groupingBy(Function, Supplier, Collector)
1099      */
1100     public static <T, K, A, D, M extends ConcurrentMap<K, D>>
1101     Collector<T, ?, M> groupingByConcurrent(Function<? super T, ? extends K> classifier,
1102                                             Supplier<M> mapFactory,
1103                                             Collector<? super T, A, D> downstream) {
1104         Supplier<A> downstreamSupplier = downstream.supplier();
1105         BiConsumer<A, ? super T> downstreamAccumulator = downstream.accumulator();
1106         BinaryOperator<ConcurrentMap<K, A>> merger = Collectors.<K, A, ConcurrentMap<K, A>>mapMerger(downstream.combiner());
1107         @SuppressWarnings("unchecked")
1108         Supplier<ConcurrentMap<K, A>> mangledFactory = (Supplier<ConcurrentMap<K, A>>) mapFactory;
1109         BiConsumer<ConcurrentMap<K, A>, T> accumulator;
1110         if (downstream.characteristics().contains(Collector.Characteristics.CONCURRENT)) {
1111             accumulator = (m, t) -> {
1112                 K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key");
1113                 A resultContainer = m.computeIfAbsent(key, k -> downstreamSupplier.get());
1114                 downstreamAccumulator.accept(resultContainer, t);
1115             };
1116         }
1117         else {
1118             accumulator = (m, t) -> {
1119                 K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key");
1120                 A resultContainer = m.computeIfAbsent(key, k -> downstreamSupplier.get());
1121                 synchronized (resultContainer) {
1122                     downstreamAccumulator.accept(resultContainer, t);
1123                 }
1124             };
1125         }
1126 
1127         if (downstream.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)) {
1128             return new CollectorImpl<>(mangledFactory, accumulator, merger, CH_CONCURRENT_ID);
1129         }
1130         else {
1131             @SuppressWarnings("unchecked")
1132             Function<A, A> downstreamFinisher = (Function<A, A>) downstream.finisher();
1133             Function<ConcurrentMap<K, A>, M> finisher = intermediate -> {
1134                 intermediate.replaceAll((k, v) -> downstreamFinisher.apply(v));
1135                 @SuppressWarnings("unchecked")
1136                 M castResult = (M) intermediate;
1137                 return castResult;
1138             };
1139             return new CollectorImpl<>(mangledFactory, accumulator, merger, finisher, CH_CONCURRENT_NOID);
1140         }
1141     }
1142 
1143     /**
1144      * Returns a {@code Collector} which partitions the input elements according
1145      * to a {@code Predicate}, and organizes them into a
1146      * {@code Map<Boolean, List<T>>}.
1147      *
1148      * There are no guarantees on the type, mutability,
1149      * serializability, or thread-safety of the {@code Map} or {@code List}
1150      * returned.
1151      *
1152      * @param <T> the type of the input elements
1153      * @param predicate a predicate used for classifying input elements
1154      * @return a {@code Collector} implementing the partitioning operation
1155      *
1156      * @see #partitioningBy(Predicate, Collector)
1157      */
1158     public static <T>
1159     Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate) {
1160         return partitioningBy(predicate, toList());
1161     }
1162 
1163     /**
1164      * Returns a {@code Collector} which partitions the input elements according
1165      * to a {@code Predicate}, reduces the values in each partition according to
1166      * another {@code Collector}, and organizes them into a
1167      * {@code Map<Boolean, D>} whose values are the result of the downstream
1168      * reduction.
1169      *
1170      * <p>There are no guarantees on the type, mutability,
1171      * serializability, or thread-safety of the {@code Map} returned.
1172      *
1173      * @param <T> the type of the input elements
1174      * @param <A> the intermediate accumulation type of the downstream collector
1175      * @param <D> the result type of the downstream reduction
1176      * @param predicate a predicate used for classifying input elements
1177      * @param downstream a {@code Collector} implementing the downstream
1178      *                   reduction
1179      * @return a {@code Collector} implementing the cascaded partitioning
1180      *         operation
1181      *
1182      * @see #partitioningBy(Predicate)
1183      */
1184     public static <T, D, A>
1185     Collector<T, ?, Map<Boolean, D>> partitioningBy(Predicate<? super T> predicate,
1186                                                     Collector<? super T, A, D> downstream) {
1187         BiConsumer<A, ? super T> downstreamAccumulator = downstream.accumulator();
1188         BiConsumer<Partition<A>, T> accumulator = (result, t) ->
1189                 downstreamAccumulator.accept(predicate.test(t) ? result.forTrue : result.forFalse, t);
1190         BinaryOperator<A> op = downstream.combiner();
1191         BinaryOperator<Partition<A>> merger = (left, right) ->
1192                 new Partition<>(op.apply(left.forTrue, right.forTrue),
1193                                 op.apply(left.forFalse, right.forFalse));
1194         Supplier<Partition<A>> supplier = () ->
1195                 new Partition<>(downstream.supplier().get(),
1196                                 downstream.supplier().get());
1197         if (downstream.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)) {
1198             return new CollectorImpl<>(supplier, accumulator, merger, CH_ID);
1199         }
1200         else {
1201             Function<Partition<A>, Map<Boolean, D>> finisher = par ->
1202                     new Partition<>(downstream.finisher().apply(par.forTrue),
1203                                     downstream.finisher().apply(par.forFalse));
1204             return new CollectorImpl<>(supplier, accumulator, merger, finisher, CH_NOID);
1205         }
1206     }
1207 
1208     /**
1209      * Returns a {@code Collector} that accumulates elements into a
1210      * {@code Map} whose keys and values are the result of applying the provided
1211      * mapping functions to the input elements.
1212      *
1213      * <p>If the mapped keys contains duplicates (according to
1214      * {@link Object#equals(Object)}), an {@code IllegalStateException} is
1215      * thrown when the collection operation is performed.  If the mapped keys
1216      * may have duplicates, use {@link #toMap(Function, Function, BinaryOperator)}
1217      * instead.
1218      *
1219      * <p>There are no guarantees on the type, mutability, serializability,
1220      * or thread-safety of the {@code Map} returned.
1221      *
1222      * @apiNote
1223      * It is common for either the key or the value to be the input elements.
1224      * In this case, the utility method
1225      * {@link java.util.function.Function#identity()} may be helpful.
1226      * For example, the following produces a {@code Map} mapping
1227      * students to their grade point average:
1228      * <pre>{@code
1229      *     Map<Student, Double> studentToGPA
1230      *         students.stream().collect(toMap(Function.identity(),
1231      *                                         student -> computeGPA(student)));
1232      * }</pre>
1233      * And the following produces a {@code Map} mapping a unique identifier to
1234      * students:
1235      * <pre>{@code
1236      *     Map<String, Student> studentIdToStudent
1237      *         students.stream().collect(toMap(Student::getId,
1238      *                                         Function.identity());
1239      * }</pre>
1240      *
1241      * @implNote
1242      * The returned {@code Collector} is not concurrent.  For parallel stream
1243      * pipelines, the {@code combiner} function operates by merging the keys
1244      * from one map into another, which can be an expensive operation.  If it is
1245      * not required that results are inserted into the {@code Map} in encounter
1246      * order, using {@link #toConcurrentMap(Function, Function)}
1247      * may offer better parallel performance.
1248      *
1249      * @param <T> the type of the input elements
1250      * @param <K> the output type of the key mapping function
1251      * @param <U> the output type of the value mapping function
1252      * @param keyMapper a mapping function to produce keys
1253      * @param valueMapper a mapping function to produce values
1254      * @return a {@code Collector} which collects elements into a {@code Map}
1255      * whose keys and values are the result of applying mapping functions to
1256      * the input elements
1257      *
1258      * @see #toMap(Function, Function, BinaryOperator)
1259      * @see #toMap(Function, Function, BinaryOperator, Supplier)
1260      * @see #toConcurrentMap(Function, Function)
1261      */
1262     public static <T, K, U>
1263     Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
1264                                     Function<? super T, ? extends U> valueMapper) {
1265         return new CollectorImpl<>(HashMap::new,
1266                                    uniqKeysMapAccumulator(keyMapper, valueMapper),
1267                                    uniqKeysMapMerger(),
1268                                    CH_ID);
1269     }
1270 
1271     /**
1272      * Returns a {@code Collector} that accumulates elements into a
1273      * {@code Map} whose keys and values are the result of applying the provided
1274      * mapping functions to the input elements.
1275      *
1276      * <p>If the mapped
1277      * keys contains duplicates (according to {@link Object#equals(Object)}),
1278      * the value mapping function is applied to each equal element, and the
1279      * results are merged using the provided merging function.
1280      *
1281      * <p>There are no guarantees on the type, mutability, serializability,
1282      * or thread-safety of the {@code Map} returned.
1283      *
1284      * @apiNote
1285      * There are multiple ways to deal with collisions between multiple elements
1286      * mapping to the same key.  The other forms of {@code toMap} simply use
1287      * a merge function that throws unconditionally, but you can easily write
1288      * more flexible merge policies.  For example, if you have a stream
1289      * of {@code Person}, and you want to produce a "phone book" mapping name to
1290      * address, but it is possible that two persons have the same name, you can
1291      * do as follows to gracefully deals with these collisions, and produce a
1292      * {@code Map} mapping names to a concatenated list of addresses:
1293      * <pre>{@code
1294      *     Map<String, String> phoneBook
1295      *         people.stream().collect(toMap(Person::getName,
1296      *                                       Person::getAddress,
1297      *                                       (s, a) -> s + ", " + a));
1298      * }</pre>
1299      *
1300      * @implNote
1301      * The returned {@code Collector} is not concurrent.  For parallel stream
1302      * pipelines, the {@code combiner} function operates by merging the keys
1303      * from one map into another, which can be an expensive operation.  If it is
1304      * not required that results are merged into the {@code Map} in encounter
1305      * order, using {@link #toConcurrentMap(Function, Function, BinaryOperator)}
1306      * may offer better parallel performance.
1307      *
1308      * @param <T> the type of the input elements
1309      * @param <K> the output type of the key mapping function
1310      * @param <U> the output type of the value mapping function
1311      * @param keyMapper a mapping function to produce keys
1312      * @param valueMapper a mapping function to produce values
1313      * @param mergeFunction a merge function, used to resolve collisions between
1314      *                      values associated with the same key, as supplied
1315      *                      to {@link Map#merge(Object, Object, BiFunction)}
1316      * @return a {@code Collector} which collects elements into a {@code Map}
1317      * whose keys are the result of applying a key mapping function to the input
1318      * elements, and whose values are the result of applying a value mapping
1319      * function to all input elements equal to the key and combining them
1320      * using the merge function
1321      *
1322      * @see #toMap(Function, Function)
1323      * @see #toMap(Function, Function, BinaryOperator, Supplier)
1324      * @see #toConcurrentMap(Function, Function, BinaryOperator)
1325      */
1326     public static <T, K, U>
1327     Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
1328                                     Function<? super T, ? extends U> valueMapper,
1329                                     BinaryOperator<U> mergeFunction) {
1330         return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
1331     }
1332 
1333     /**
1334      * Returns a {@code Collector} that accumulates elements into a
1335      * {@code Map} whose keys and values are the result of applying the provided
1336      * mapping functions to the input elements.
1337      *
1338      * <p>If the mapped
1339      * keys contains duplicates (according to {@link Object#equals(Object)}),
1340      * the value mapping function is applied to each equal element, and the
1341      * results are merged using the provided merging function.  The {@code Map}
1342      * is created by a provided supplier function.
1343      *
1344      * @implNote
1345      * The returned {@code Collector} is not concurrent.  For parallel stream
1346      * pipelines, the {@code combiner} function operates by merging the keys
1347      * from one map into another, which can be an expensive operation.  If it is
1348      * not required that results are merged into the {@code Map} in encounter
1349      * order, using {@link #toConcurrentMap(Function, Function, BinaryOperator, Supplier)}
1350      * may offer better parallel performance.
1351      *
1352      * @param <T> the type of the input elements
1353      * @param <K> the output type of the key mapping function
1354      * @param <U> the output type of the value mapping function
1355      * @param <M> the type of the resulting {@code Map}
1356      * @param keyMapper a mapping function to produce keys
1357      * @param valueMapper a mapping function to produce values
1358      * @param mergeFunction a merge function, used to resolve collisions between
1359      *                      values associated with the same key, as supplied
1360      *                      to {@link Map#merge(Object, Object, BiFunction)}
1361      * @param mapSupplier a function which returns a new, empty {@code Map} into
1362      *                    which the results will be inserted
1363      * @return a {@code Collector} which collects elements into a {@code Map}
1364      * whose keys are the result of applying a key mapping function to the input
1365      * elements, and whose values are the result of applying a value mapping
1366      * function to all input elements equal to the key and combining them
1367      * using the merge function
1368      *
1369      * @see #toMap(Function, Function)
1370      * @see #toMap(Function, Function, BinaryOperator)
1371      * @see #toConcurrentMap(Function, Function, BinaryOperator, Supplier)
1372      */
1373     public static <T, K, U, M extends Map<K, U>>
1374     Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
1375                                 Function<? super T, ? extends U> valueMapper,
1376                                 BinaryOperator<U> mergeFunction,
1377                                 Supplier<M> mapSupplier) {
1378         BiConsumer<M, T> accumulator
1379                 = (map, element) -> map.merge(keyMapper.apply(element),
1380                                               valueMapper.apply(element), mergeFunction);
1381         return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID);
1382     }
1383 
1384     /**
1385      * Returns a concurrent {@code Collector} that accumulates elements into a
1386      * {@code ConcurrentMap} whose keys and values are the result of applying
1387      * the provided mapping functions to the input elements.
1388      *
1389      * <p>If the mapped keys contains duplicates (according to
1390      * {@link Object#equals(Object)}), an {@code IllegalStateException} is
1391      * thrown when the collection operation is performed.  If the mapped keys
1392      * may have duplicates, use
1393      * {@link #toConcurrentMap(Function, Function, BinaryOperator)} instead.
1394      *
1395      * <p>There are no guarantees on the type, mutability, or serializability
1396      * of the {@code ConcurrentMap} returned.
1397      *
1398      * @apiNote
1399      * It is common for either the key or the value to be the input elements.
1400      * In this case, the utility method
1401      * {@link java.util.function.Function#identity()} may be helpful.
1402      * For example, the following produces a {@code Map} mapping
1403      * students to their grade point average:
1404      * <pre>{@code
1405      *     Map<Student, Double> studentToGPA
1406      *         students.stream().collect(toMap(Function.identity(),
1407      *                                         student -> computeGPA(student)));
1408      * }</pre>
1409      * And the following produces a {@code Map} mapping a unique identifier to
1410      * students:
1411      * <pre>{@code
1412      *     Map<String, Student> studentIdToStudent
1413      *         students.stream().collect(toConcurrentMap(Student::getId,
1414      *                                                   Function.identity());
1415      * }</pre>
1416      *
1417      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
1418      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
1419      *
1420      * @param <T> the type of the input elements
1421      * @param <K> the output type of the key mapping function
1422      * @param <U> the output type of the value mapping function
1423      * @param keyMapper the mapping function to produce keys
1424      * @param valueMapper the mapping function to produce values
1425      * @return a concurrent, unordered {@code Collector} which collects elements into a
1426      * {@code ConcurrentMap} whose keys are the result of applying a key mapping
1427      * function to the input elements, and whose values are the result of
1428      * applying a value mapping function to the input elements
1429      *
1430      * @see #toMap(Function, Function)
1431      * @see #toConcurrentMap(Function, Function, BinaryOperator)
1432      * @see #toConcurrentMap(Function, Function, BinaryOperator, Supplier)
1433      */
1434     public static <T, K, U>
1435     Collector<T, ?, ConcurrentMap<K,U>> toConcurrentMap(Function<? super T, ? extends K> keyMapper,
1436                                                         Function<? super T, ? extends U> valueMapper) {
1437         return new CollectorImpl<>(ConcurrentHashMap::new,
1438                                    uniqKeysMapAccumulator(keyMapper, valueMapper),
1439                                    uniqKeysMapMerger(),
1440                                    CH_CONCURRENT_ID);
1441     }
1442 
1443     /**
1444      * Returns a concurrent {@code Collector} that accumulates elements into a
1445      * {@code ConcurrentMap} whose keys and values are the result of applying
1446      * the provided mapping functions to the input elements.
1447      *
1448      * <p>If the mapped keys contains duplicates (according to {@link Object#equals(Object)}),
1449      * the value mapping function is applied to each equal element, and the
1450      * results are merged using the provided merging function.
1451      *
1452      * <p>There are no guarantees on the type, mutability, or serializability
1453      * of the {@code ConcurrentMap} returned.
1454      *
1455      * @apiNote
1456      * There are multiple ways to deal with collisions between multiple elements
1457      * mapping to the same key.  The other forms of {@code toConcurrentMap} simply use
1458      * a merge function that throws unconditionally, but you can easily write
1459      * more flexible merge policies.  For example, if you have a stream
1460      * of {@code Person}, and you want to produce a "phone book" mapping name to
1461      * address, but it is possible that two persons have the same name, you can
1462      * do as follows to gracefully deals with these collisions, and produce a
1463      * {@code Map} mapping names to a concatenated list of addresses:
1464      * <pre>{@code
1465      *     Map<String, String> phoneBook
1466      *         people.stream().collect(toConcurrentMap(Person::getName,
1467      *                                                 Person::getAddress,
1468      *                                                 (s, a) -> s + ", " + a));
1469      * }</pre>
1470      *
1471      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
1472      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
1473      *
1474      * @param <T> the type of the input elements
1475      * @param <K> the output type of the key mapping function
1476      * @param <U> the output type of the value mapping function
1477      * @param keyMapper a mapping function to produce keys
1478      * @param valueMapper a mapping function to produce values
1479      * @param mergeFunction a merge function, used to resolve collisions between
1480      *                      values associated with the same key, as supplied
1481      *                      to {@link Map#merge(Object, Object, BiFunction)}
1482      * @return a concurrent, unordered {@code Collector} which collects elements into a
1483      * {@code ConcurrentMap} whose keys are the result of applying a key mapping
1484      * function to the input elements, and whose values are the result of
1485      * applying a value mapping function to all input elements equal to the key
1486      * and combining them using the merge function
1487      *
1488      * @see #toConcurrentMap(Function, Function)
1489      * @see #toConcurrentMap(Function, Function, BinaryOperator, Supplier)
1490      * @see #toMap(Function, Function, BinaryOperator)
1491      */
1492     public static <T, K, U>
1493     Collector<T, ?, ConcurrentMap<K,U>>
1494     toConcurrentMap(Function<? super T, ? extends K> keyMapper,
1495                     Function<? super T, ? extends U> valueMapper,
1496                     BinaryOperator<U> mergeFunction) {
1497         return toConcurrentMap(keyMapper, valueMapper, mergeFunction, ConcurrentHashMap::new);
1498     }
1499 
1500     /**
1501      * Returns a concurrent {@code Collector} that accumulates elements into a
1502      * {@code ConcurrentMap} whose keys and values are the result of applying
1503      * the provided mapping functions to the input elements.
1504      *
1505      * <p>If the mapped keys contains duplicates (according to {@link Object#equals(Object)}),
1506      * the value mapping function is applied to each equal element, and the
1507      * results are merged using the provided merging function.  The
1508      * {@code ConcurrentMap} is created by a provided supplier function.
1509      *
1510      * <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and
1511      * {@link Collector.Characteristics#UNORDERED unordered} Collector.
1512      *
1513      * @param <T> the type of the input elements
1514      * @param <K> the output type of the key mapping function
1515      * @param <U> the output type of the value mapping function
1516      * @param <M> the type of the resulting {@code ConcurrentMap}
1517      * @param keyMapper a mapping function to produce keys
1518      * @param valueMapper a mapping function to produce values
1519      * @param mergeFunction a merge function, used to resolve collisions between
1520      *                      values associated with the same key, as supplied
1521      *                      to {@link Map#merge(Object, Object, BiFunction)}
1522      * @param mapSupplier a function which returns a new, empty {@code Map} into
1523      *                    which the results will be inserted
1524      * @return a concurrent, unordered {@code Collector} which collects elements into a
1525      * {@code ConcurrentMap} whose keys are the result of applying a key mapping
1526      * function to the input elements, and whose values are the result of
1527      * applying a value mapping function to all input elements equal to the key
1528      * and combining them using the merge function
1529      *
1530      * @see #toConcurrentMap(Function, Function)
1531      * @see #toConcurrentMap(Function, Function, BinaryOperator)
1532      * @see #toMap(Function, Function, BinaryOperator, Supplier)
1533      */
1534     public static <T, K, U, M extends ConcurrentMap<K, U>>
1535     Collector<T, ?, M> toConcurrentMap(Function<? super T, ? extends K> keyMapper,
1536                                        Function<? super T, ? extends U> valueMapper,
1537                                        BinaryOperator<U> mergeFunction,
1538                                        Supplier<M> mapSupplier) {
1539         BiConsumer<M, T> accumulator
1540                 = (map, element) -> map.merge(keyMapper.apply(element),
1541                                               valueMapper.apply(element), mergeFunction);
1542         return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_CONCURRENT_ID);
1543     }
1544 
1545     /**
1546      * Returns a {@code Collector} which applies an {@code int}-producing
1547      * mapping function to each input element, and returns summary statistics
1548      * for the resulting values.
1549      *
1550      * @param <T> the type of the input elements
1551      * @param mapper a mapping function to apply to each element
1552      * @return a {@code Collector} implementing the summary-statistics reduction
1553      *
1554      * @see #summarizingDouble(ToDoubleFunction)
1555      * @see #summarizingLong(ToLongFunction)
1556      */
1557     public static <T>
1558     Collector<T, ?, IntSummaryStatistics> summarizingInt(ToIntFunction<? super T> mapper) {
1559         return new CollectorImpl<T, IntSummaryStatistics, IntSummaryStatistics>(
1560                 IntSummaryStatistics::new,
1561                 (r, t) -> r.accept(mapper.applyAsInt(t)),
1562                 (l, r) -> { l.combine(r); return l; }, CH_ID);
1563     }
1564 
1565     /**
1566      * Returns a {@code Collector} which applies an {@code long}-producing
1567      * mapping function to each input element, and returns summary statistics
1568      * for the resulting values.
1569      *
1570      * @param <T> the type of the input elements
1571      * @param mapper the mapping function to apply to each element
1572      * @return a {@code Collector} implementing the summary-statistics reduction
1573      *
1574      * @see #summarizingDouble(ToDoubleFunction)
1575      * @see #summarizingInt(ToIntFunction)
1576      */
1577     public static <T>
1578     Collector<T, ?, LongSummaryStatistics> summarizingLong(ToLongFunction<? super T> mapper) {
1579         return new CollectorImpl<T, LongSummaryStatistics, LongSummaryStatistics>(
1580                 LongSummaryStatistics::new,
1581                 (r, t) -> r.accept(mapper.applyAsLong(t)),
1582                 (l, r) -> { l.combine(r); return l; }, CH_ID);
1583     }
1584 
1585     /**
1586      * Returns a {@code Collector} which applies an {@code double}-producing
1587      * mapping function to each input element, and returns summary statistics
1588      * for the resulting values.
1589      *
1590      * @param <T> the type of the input elements
1591      * @param mapper a mapping function to apply to each element
1592      * @return a {@code Collector} implementing the summary-statistics reduction
1593      *
1594      * @see #summarizingLong(ToLongFunction)
1595      * @see #summarizingInt(ToIntFunction)
1596      */
1597     public static <T>
1598     Collector<T, ?, DoubleSummaryStatistics> summarizingDouble(ToDoubleFunction<? super T> mapper) {
1599         return new CollectorImpl<T, DoubleSummaryStatistics, DoubleSummaryStatistics>(
1600                 DoubleSummaryStatistics::new,
1601                 (r, t) -> r.accept(mapper.applyAsDouble(t)),
1602                 (l, r) -> { l.combine(r); return l; }, CH_ID);
1603     }
1604 
1605     /**
1606      * Implementation class used by partitioningBy.
1607      */
1608     private static final class Partition<T>
1609             extends AbstractMap<Boolean, T>
1610             implements Map<Boolean, T> {
1611         final T forTrue;
1612         final T forFalse;
1613 
1614         Partition(T forTrue, T forFalse) {
1615             this.forTrue = forTrue;
1616             this.forFalse = forFalse;
1617         }
1618 
1619         @Override
1620         public Set<Map.Entry<Boolean, T>> entrySet() {
1621             return new AbstractSet<Map.Entry<Boolean, T>>() {
1622                 @Override
1623                 public Iterator<Map.Entry<Boolean, T>> iterator() {
1624                     Map.Entry<Boolean, T> falseEntry = new SimpleImmutableEntry<>(false, forFalse);
1625                     Map.Entry<Boolean, T> trueEntry = new SimpleImmutableEntry<>(true, forTrue);
1626                     return Arrays.asList(falseEntry, trueEntry).iterator();
1627                 }
1628 
1629                 @Override
1630                 public int size() {
1631                     return 2;
1632                 }
1633             };
1634         }
1635     }
1636 }