001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.collect.CollectPreconditions.checkNonnegative;
021import static java.util.Arrays.asList;
022import static java.util.Arrays.sort;
023import static java.util.Collections.emptyList;
024import static java.util.Collections.sort;
025import static java.util.Collections.unmodifiableList;
026
027import com.google.common.annotations.GwtCompatible;
028import com.google.common.annotations.J2ktIncompatible;
029import com.google.common.annotations.VisibleForTesting;
030import com.google.common.base.Function;
031import com.google.errorprone.annotations.InlineMe;
032import com.google.errorprone.annotations.InlineMeValidationDisabled;
033import java.util.ArrayList;
034import java.util.Arrays;
035import java.util.Collection;
036import java.util.Collections;
037import java.util.Comparator;
038import java.util.HashSet;
039import java.util.Iterator;
040import java.util.List;
041import java.util.Map.Entry;
042import java.util.NoSuchElementException;
043import java.util.SortedMap;
044import java.util.SortedSet;
045import java.util.TreeSet;
046import java.util.concurrent.ConcurrentMap;
047import java.util.concurrent.atomic.AtomicInteger;
048import org.jspecify.annotations.NonNull;
049import org.jspecify.annotations.Nullable;
050
051/**
052 * A comparator, with additional methods to support common operations. This is an "enriched" version
053 * of {@code Comparator} for pre-Java-8 users, in the same sense that {@link FluentIterable} is an
054 * enriched {@link Iterable} for pre-Java-8 users.
055 *
056 * <h3>Three types of methods</h3>
057 *
058 * Like other fluent types, there are three types of methods present: methods for <i>acquiring</i>,
059 * <i>chaining</i>, and <i>using</i>.
060 *
061 * <h4>Acquiring</h4>
062 *
063 * <p>The common ways to get an instance of {@code Ordering} are:
064 *
065 * <ul>
066 *   <li>Subclass it and implement {@link #compare} instead of implementing {@link Comparator}
067 *       directly
068 *   <li>Pass a <i>pre-existing</i> {@link Comparator} instance to {@link #from(Comparator)}
069 *   <li>Use the natural ordering, {@link Ordering#natural}
070 * </ul>
071 *
072 * <h4>Chaining</h4>
073 *
074 * <p>Then you can use the <i>chaining</i> methods to get an altered version of that {@code
075 * Ordering}, including:
076 *
077 * <ul>
078 *   <li>{@link #reverse}
079 *   <li>{@link #compound(Comparator)}
080 *   <li>{@link #onResultOf(Function)}
081 *   <li>{@link #nullsFirst} / {@link #nullsLast}
082 * </ul>
083 *
084 * <h4>Using</h4>
085 *
086 * <p>Finally, use the resulting {@code Ordering} anywhere a {@link Comparator} is required, or use
087 * any of its special operations, such as:
088 *
089 * <ul>
090 *   <li>{@link #immutableSortedCopy}
091 *   <li>{@link #isOrdered} / {@link #isStrictlyOrdered}
092 *   <li>{@link #min} / {@link #max}
093 * </ul>
094 *
095 * <h3>Understanding complex orderings</h3>
096 *
097 * <p>Complex chained orderings like the following example can be challenging to understand.
098 *
099 * <pre>{@code
100 * Ordering<Foo> ordering =
101 *     Ordering.natural()
102 *         .nullsFirst()
103 *         .onResultOf(getBarFunction)
104 *         .nullsLast();
105 * }</pre>
106 *
107 * Note that each chaining method returns a new ordering instance which is backed by the previous
108 * instance, but has the chance to act on values <i>before</i> handing off to that backing instance.
109 * As a result, it usually helps to read chained ordering expressions <i>backwards</i>. For example,
110 * when {@code compare} is called on the above ordering:
111 *
112 * <ol>
113 *   <li>First, if only one {@code Foo} is null, that null value is treated as <i>greater</i>
114 *   <li>Next, non-null {@code Foo} values are passed to {@code getBarFunction} (we will be
115 *       comparing {@code Bar} values from now on)
116 *   <li>Next, if only one {@code Bar} is null, that null value is treated as <i>lesser</i>
117 *   <li>Finally, natural ordering is used (i.e. the result of {@code Bar.compareTo(Bar)} is
118 *       returned)
119 * </ol>
120 *
121 * <p>Alas, {@link #reverse} is a little different. As you read backwards through a chain and
122 * encounter a call to {@code reverse}, continue working backwards until a result is determined, and
123 * then reverse that result.
124 *
125 * <h3>Additional notes</h3>
126 *
127 * <p>Except as noted, the orderings returned by the factory methods of this class are serializable
128 * if and only if the provided instances that back them are. For example, if {@code ordering} and
129 * {@code function} can themselves be serialized, then {@code ordering.onResultOf(function)} can as
130 * well.
131 *
132 * <h3>Java 8+ users</h3>
133 *
134 * <p>If you are using Java 8+, this class is now obsolete. Most of its functionality is now
135 * provided by {@link java.util.stream.Stream Stream} and by {@link Comparator} itself, and the rest
136 * can now be found as static methods in our new {@link Comparators} class. See each method below
137 * for further instructions. Whenever possible, you should change any references of type {@code
138 * Ordering} to be of type {@code Comparator} instead. However, at this time we have no plan to
139 * <i>deprecate</i> this class.
140 *
141 * <p>Many replacements involve adopting {@code Stream}, and these changes can sometimes make your
142 * code verbose. Whenever following this advice, you should check whether {@code Stream} could be
143 * adopted more comprehensively in your code; the end result may be quite a bit simpler.
144 *
145 * <h3>See also</h3>
146 *
147 * <p>See the Guava User Guide article on <a href=
148 * "https://github.com/google/guava/wiki/OrderingExplained">{@code Ordering}</a>.
149 *
150 * @author Jesse Wilson
151 * @author Kevin Bourrillion
152 * @since 2.0
153 */
154@GwtCompatible
155public abstract class Ordering<T extends @Nullable Object> implements Comparator<T> {
156  // Natural order
157
158  /**
159   * Returns a serializable ordering that uses the natural order of the values. The ordering throws
160   * a {@link NullPointerException} when passed a null parameter.
161   *
162   * <p>The type specification is {@code <C extends Comparable>}, instead of the technically correct
163   * {@code <C extends Comparable<? super C>>}, to support legacy types from before Java 5.
164   *
165   * <p><b>Java 8+ users:</b> use {@link Comparator#naturalOrder} instead.
166   */
167  @GwtCompatible(serializable = true)
168  @SuppressWarnings({"unchecked", "rawtypes"})
169  // TODO(kevinb): right way to explain this??
170  // plus https://github.com/google/guava/issues/989
171  public static <C extends Comparable> Ordering<C> natural() {
172    return (Ordering<C>) NaturalOrdering.INSTANCE;
173  }
174
175  // Static factories
176
177  /**
178   * Returns an ordering based on an <i>existing</i> comparator instance. Note that it is
179   * unnecessary to create a <i>new</i> anonymous inner class implementing {@code Comparator} just
180   * to pass it in here. Instead, simply subclass {@code Ordering} and implement its {@code compare}
181   * method directly.
182   *
183   * <p>The returned object is serializable if {@code comparator} is serializable.
184   *
185   * <p><b>Java 8+ users:</b> this class is now obsolete as explained in the class documentation, so
186   * there is no need to use this method.
187   *
188   * @param comparator the comparator that defines the order
189   * @return comparator itself if it is already an {@code Ordering}; otherwise an ordering that
190   *     wraps that comparator
191   */
192  @GwtCompatible(serializable = true)
193  public static <T extends @Nullable Object> Ordering<T> from(Comparator<T> comparator) {
194    return (comparator instanceof Ordering)
195        ? (Ordering<T>) comparator
196        : new ComparatorOrdering<T>(comparator);
197  }
198
199  /**
200   * Simply returns its argument.
201   *
202   * @deprecated no need to use this
203   */
204  @InlineMe(
205      replacement = "checkNotNull(ordering)",
206      staticImports = "com.google.common.base.Preconditions.checkNotNull")
207  @GwtCompatible(serializable = true)
208  @Deprecated
209  public static <T extends @Nullable Object> Ordering<T> from(Ordering<T> ordering) {
210    return checkNotNull(ordering);
211  }
212
213  /**
214   * Returns an ordering that compares objects according to the order in which they appear in the
215   * given list. Only objects present in the list (according to {@link Object#equals}) may be
216   * compared. This comparator imposes a "partial ordering" over the type {@code T}. Subsequent
217   * changes to the {@code valuesInOrder} list will have no effect on the returned comparator. Null
218   * values in the list are not supported.
219   *
220   * <p>The returned comparator throws a {@link ClassCastException} when it receives an input
221   * parameter that isn't among the provided values.
222   *
223   * <p>The generated comparator is serializable if all the provided values are serializable.
224   *
225   * @param valuesInOrder the values that the returned comparator will be able to compare, in the
226   *     order the comparator should induce
227   * @return the comparator described above
228   * @throws NullPointerException if any of the provided values is null
229   * @throws IllegalArgumentException if {@code valuesInOrder} contains any duplicate values
230   *     (according to {@link Object#equals})
231   */
232  // TODO(kevinb): provide replacement
233  @GwtCompatible(serializable = true)
234  public static <T> Ordering<T> explicit(List<T> valuesInOrder) {
235    return new ExplicitOrdering<>(valuesInOrder);
236  }
237
238  /**
239   * Returns an ordering that compares objects according to the order in which they are given to
240   * this method. Only objects present in the argument list (according to {@link Object#equals}) may
241   * be compared. This comparator imposes a "partial ordering" over the type {@code T}. Null values
242   * in the argument list are not supported.
243   *
244   * <p>The returned comparator throws a {@link ClassCastException} when it receives an input
245   * parameter that isn't among the provided values.
246   *
247   * <p>The generated comparator is serializable if all the provided values are serializable.
248   *
249   * @param leastValue the value which the returned comparator should consider the "least" of all
250   *     values
251   * @param remainingValuesInOrder the rest of the values that the returned comparator will be able
252   *     to compare, in the order the comparator should follow
253   * @return the comparator described above
254   * @throws NullPointerException if any of the provided values is null
255   * @throws IllegalArgumentException if any duplicate values (according to {@link
256   *     Object#equals(Object)}) are present among the method arguments
257   */
258  // TODO(kevinb): provide replacement
259  @GwtCompatible(serializable = true)
260  public static <T> Ordering<T> explicit(T leastValue, T... remainingValuesInOrder) {
261    return explicit(Lists.asList(leastValue, remainingValuesInOrder));
262  }
263
264  // Ordering<Object> singletons
265
266  /**
267   * Returns an ordering which treats all values as equal, indicating "no ordering." Passing this
268   * ordering to any <i>stable</i> sort algorithm results in no change to the order of elements.
269   * Note especially that {@link #sortedCopy} and {@link #immutableSortedCopy} are stable, and in
270   * the returned instance these are implemented by simply copying the source list.
271   *
272   * <p>Example:
273   *
274   * <pre>{@code
275   * Ordering.allEqual().nullsLast().sortedCopy(
276   *     asList(t, null, e, s, null, t, null))
277   * }</pre>
278   *
279   * <p>Assuming {@code t}, {@code e} and {@code s} are non-null, this returns {@code [t, e, s, t,
280   * null, null, null]} regardless of the true comparison order of those three values (which might
281   * not even implement {@link Comparable} at all).
282   *
283   * <p><b>Warning:</b> by definition, this comparator is not <i>consistent with equals</i> (as
284   * defined {@linkplain Comparator here}). Avoid its use in APIs, such as {@link
285   * TreeSet#TreeSet(Comparator)}, where such consistency is expected.
286   *
287   * <p>The returned comparator is serializable.
288   *
289   * <p><b>Java 8+ users:</b> Use the lambda expression {@code (a, b) -> 0} instead (in certain
290   * cases you may need to cast that to {@code Comparator<YourType>}).
291   *
292   * @since 13.0
293   */
294  @GwtCompatible(serializable = true)
295  public static Ordering<@Nullable Object> allEqual() {
296    return AllEqualOrdering.INSTANCE;
297  }
298
299  /**
300   * Returns an ordering that compares objects by the natural ordering of their string
301   * representations as returned by {@code toString()}. It does not support null values.
302   *
303   * <p>The comparator is serializable.
304   *
305   * <p><b>Java 8+ users:</b> Use {@code Comparator.comparing(Object::toString)} instead.
306   */
307  @GwtCompatible(serializable = true)
308  public static Ordering<Object> usingToString() {
309    return UsingToStringOrdering.INSTANCE;
310  }
311
312  /**
313   * Returns an arbitrary ordering over all objects, for which {@code compare(a, b) == 0} implies
314   * {@code a == b} (identity equality). There is no meaning whatsoever to the order imposed, but it
315   * is constant for the life of the VM.
316   *
317   * <p>Because the ordering is identity-based, it is not "consistent with {@link
318   * Object#equals(Object)}" as defined by {@link Comparator}. Use caution when building a {@link
319   * SortedSet} or {@link SortedMap} from it, as the resulting collection will not behave exactly
320   * according to spec.
321   *
322   * <p>This ordering is not serializable, as its implementation relies on {@link
323   * System#identityHashCode(Object)}, so its behavior cannot be preserved across serialization.
324   *
325   * @since 2.0
326   */
327  // TODO(kevinb): copy to Comparators, etc.
328  @J2ktIncompatible // MapMaker
329  public static Ordering<@Nullable Object> arbitrary() {
330    return ArbitraryOrderingHolder.ARBITRARY_ORDERING;
331  }
332
333  @J2ktIncompatible // MapMaker
334  private static class ArbitraryOrderingHolder {
335    static final Ordering<@Nullable Object> ARBITRARY_ORDERING = new ArbitraryOrdering();
336  }
337
338  @J2ktIncompatible // MapMaker
339  @VisibleForTesting
340  static class ArbitraryOrdering extends Ordering<@Nullable Object> {
341
342    private final AtomicInteger counter = new AtomicInteger(0);
343    private final ConcurrentMap<Object, Integer> uids =
344        Platform.tryWeakKeys(new MapMaker()).makeMap();
345
346    private Integer getUid(Object obj) {
347      Integer uid = uids.get(obj);
348      if (uid == null) {
349        // One or more integer values could be skipped in the event of a race
350        // to generate a UID for the same object from multiple threads, but
351        // that shouldn't be a problem.
352        uid = counter.getAndIncrement();
353        Integer alreadySet = uids.putIfAbsent(obj, uid);
354        if (alreadySet != null) {
355          uid = alreadySet;
356        }
357      }
358      return uid;
359    }
360
361    @Override
362    public int compare(@Nullable Object left, @Nullable Object right) {
363      if (left == right) {
364        return 0;
365      } else if (left == null) {
366        return -1;
367      } else if (right == null) {
368        return 1;
369      }
370      int leftCode = identityHashCode(left);
371      int rightCode = identityHashCode(right);
372      if (leftCode != rightCode) {
373        return leftCode < rightCode ? -1 : 1;
374      }
375
376      // identityHashCode collision (rare, but not as rare as you'd think)
377      int result = getUid(left).compareTo(getUid(right));
378      if (result == 0) {
379        throw new AssertionError(); // extremely, extremely unlikely.
380      }
381      return result;
382    }
383
384    @Override
385    public String toString() {
386      return "Ordering.arbitrary()";
387    }
388
389    /*
390     * We need to be able to mock identityHashCode() calls for tests, because it
391     * can take 1-10 seconds to find colliding objects. Mocking frameworks that
392     * can do magic to mock static method calls still can't do so for a system
393     * class, so we need the indirection. In production, Hotspot should still
394     * recognize that the call is 1-morphic and should still be willing to
395     * inline it if necessary.
396     */
397    int identityHashCode(Object object) {
398      return System.identityHashCode(object);
399    }
400  }
401
402  // Constructor
403
404  /**
405   * Constructs a new instance of this class (only invokable by the subclass constructor, typically
406   * implicit).
407   */
408  protected Ordering() {}
409
410  // Instance-based factories (and any static equivalents)
411
412  /**
413   * Returns the reverse of this ordering; the {@code Ordering} equivalent to {@link
414   * Collections#reverseOrder(Comparator)}.
415   *
416   * <p><b>Java 8+ users:</b> Use {@code thisComparator.reversed()} instead.
417   */
418  // type parameter <S> lets us avoid the extra <String> in statements like:
419  // Ordering<String> o = Ordering.<String>natural().reverse();
420  @GwtCompatible(serializable = true)
421  public <S extends T> Ordering<S> reverse() {
422    return new ReverseOrdering<>(this);
423  }
424
425  /**
426   * Returns an ordering that treats {@code null} as less than all other values and uses {@code
427   * this} to compare non-null values.
428   *
429   * <p>The returned object is serializable if this object is serializable.
430   *
431   * <p><b>Java 8+ users:</b> Use {@code Comparator.nullsFirst(thisComparator)} instead.
432   */
433  // type parameter <S> lets us avoid the extra <String> in statements like:
434  // Ordering<String> o = Ordering.<String>natural().nullsFirst();
435  @GwtCompatible(serializable = true)
436  public <S extends T> Ordering<@Nullable S> nullsFirst() {
437    return new NullsFirstOrdering<S>(this);
438  }
439
440  /**
441   * Returns an ordering that treats {@code null} as greater than all other values and uses this
442   * ordering to compare non-null values.
443   *
444   * <p>The returned object is serializable if this object is serializable.
445   *
446   * <p><b>Java 8+ users:</b> Use {@code Comparator.nullsLast(thisComparator)} instead.
447   */
448  // type parameter <S> lets us avoid the extra <String> in statements like:
449  // Ordering<String> o = Ordering.<String>natural().nullsLast();
450  @GwtCompatible(serializable = true)
451  public <S extends T> Ordering<@Nullable S> nullsLast() {
452    return new NullsLastOrdering<S>(this);
453  }
454
455  /**
456   * Returns a new ordering on {@code F} which orders elements by first applying a function to them,
457   * then comparing those results using {@code this}. For example, to compare objects by their
458   * string forms, in a case-insensitive manner, use:
459   *
460   * <pre>{@code
461   * Ordering.from(String.CASE_INSENSITIVE_ORDER)
462   *     .onResultOf(Functions.toStringFunction())
463   * }</pre>
464   *
465   * <p><b>Java 8+ users:</b> Use {@code Comparator.comparing(function, thisComparator)} instead
466   * (you can omit the comparator if it is the natural order).
467   */
468  @GwtCompatible(serializable = true)
469  public <F extends @Nullable Object> Ordering<F> onResultOf(Function<F, ? extends T> function) {
470    return new ByFunctionOrdering<>(function, this);
471  }
472
473  <T2 extends T> Ordering<Entry<T2, ?>> onKeys() {
474    return onResultOf(Maps.<T2>keyFunction());
475  }
476
477  /**
478   * Returns an ordering which first uses the ordering {@code this}, but which in the event of a
479   * "tie", then delegates to {@code secondaryComparator}. For example, to sort a bug list first by
480   * status and second by priority, you might use {@code byStatus.compound(byPriority)}. For a
481   * compound ordering with three or more components, simply chain multiple calls to this method.
482   *
483   * <p>An ordering produced by this method, or a chain of calls to this method, is equivalent to
484   * one created using {@link Ordering#compound(Iterable)} on the same component comparators.
485   *
486   * <p>The returned object is serializable if this object and {@code secondaryComparator} are both
487   * serializable.
488   *
489   * <p><b>Java 8+ users:</b> Use {@code thisComparator.thenComparing(secondaryComparator)} instead.
490   * Depending on what {@code secondaryComparator} is, one of the other overloads of {@code
491   * thenComparing} may be even more useful.
492   */
493  @GwtCompatible(serializable = true)
494  public <U extends T> Ordering<U> compound(Comparator<? super U> secondaryComparator) {
495    return new CompoundOrdering<>(this, checkNotNull(secondaryComparator));
496  }
497
498  /**
499   * Returns an ordering which tries each given comparator in order until a non-zero result is
500   * found, returning that result, and returning zero only if all comparators return zero. The
501   * returned ordering is based on the state of the {@code comparators} iterable at the time it was
502   * provided to this method.
503   *
504   * <p>The returned ordering is equivalent to that produced using {@code
505   * Ordering.from(comp1).compound(comp2).compound(comp3) . . .}.
506   *
507   * <p>The returned object is serializable if each of the {@code comparators} is serializable.
508   *
509   * <p><b>Warning:</b> Supplying an argument with undefined iteration order, such as a {@link
510   * HashSet}, will produce non-deterministic results.
511   *
512   * <p><b>Java 8+ users:</b> Use a chain of calls to {@link Comparator#thenComparing(Comparator)},
513   * or {@code comparatorCollection.stream().reduce(Comparator::thenComparing).get()} (if the
514   * collection might be empty, also provide a default comparator as the {@code identity} parameter
515   * to {@code reduce}).
516   *
517   * @param comparators the comparators to try in order
518   */
519  @GwtCompatible(serializable = true)
520  public static <T extends @Nullable Object> Ordering<T> compound(
521      Iterable<? extends Comparator<? super T>> comparators) {
522    return new CompoundOrdering<>(comparators);
523  }
524
525  /**
526   * Returns a new ordering which sorts iterables by comparing corresponding elements pairwise until
527   * a nonzero result is found; imposes "dictionary order". If the end of one iterable is reached,
528   * but not the other, the shorter iterable is considered to be less than the longer one. For
529   * example, a lexicographical natural ordering over integers considers {@code [] < [1] < [1, 1] <
530   * [1, 2] < [2]}.
531   *
532   * <p>Note that {@code ordering.lexicographical().reverse()} is not equivalent to {@code
533   * ordering.reverse().lexicographical()} (consider how each would order {@code [1]} and {@code [1,
534   * 1]}).
535   *
536   * <p><b>Java 8+ users:</b> Use {@link Comparators#lexicographical(Comparator)} instead.
537   *
538   * @since 2.0
539   */
540  @GwtCompatible(serializable = true)
541  // type parameter <S> lets us avoid the extra <String> in statements like:
542  // Ordering<Iterable<String>> o =
543  //     Ordering.<String>natural().lexicographical();
544  public <S extends T> Ordering<Iterable<S>> lexicographical() {
545    /*
546     * Note that technically the returned ordering should be capable of
547     * handling not just {@code Iterable<S>} instances, but also any {@code
548     * Iterable<? extends S>}. However, the need for this comes up so rarely
549     * that it doesn't justify making everyone else deal with the very ugly
550     * wildcard.
551     */
552    return new LexicographicalOrdering<S>(this);
553  }
554
555  // Regular instance methods
556
557  @Override
558  public abstract int compare(@ParametricNullness T left, @ParametricNullness T right);
559
560  /**
561   * Returns the least of the specified values according to this ordering. If there are multiple
562   * least values, the first of those is returned. The iterator will be left exhausted: its {@code
563   * hasNext()} method will return {@code false}.
564   *
565   * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterator).min(thisComparator).get()} instead
566   * (but note that it does not guarantee which tied minimum element is returned).
567   *
568   * @param iterator the iterator whose minimum element is to be determined
569   * @throws NoSuchElementException if {@code iterator} is empty
570   * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this
571   *     ordering.
572   * @since 11.0
573   */
574  @ParametricNullness
575  public <E extends T> E min(Iterator<E> iterator) {
576    // let this throw NoSuchElementException as necessary
577    E minSoFar = iterator.next();
578
579    while (iterator.hasNext()) {
580      minSoFar = this.<E>min(minSoFar, iterator.next());
581    }
582
583    return minSoFar;
584  }
585
586  /**
587   * Returns the least of the specified values according to this ordering. If there are multiple
588   * least values, the first of those is returned.
589   *
590   * <p><b>Java 8+ users:</b> If {@code iterable} is a {@link Collection}, use {@code
591   * Collections.min(collection, thisComparator)} instead. Otherwise, use {@code
592   * Streams.stream(iterable).min(thisComparator).get()} instead. Note that these alternatives do
593   * not guarantee which tied minimum element is returned.
594   *
595   * @param iterable the iterable whose minimum element is to be determined
596   * @throws NoSuchElementException if {@code iterable} is empty
597   * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this
598   *     ordering.
599   */
600  @ParametricNullness
601  public <E extends T> E min(Iterable<E> iterable) {
602    return min(iterable.iterator());
603  }
604
605  /**
606   * Returns the lesser of the two values according to this ordering. If the values compare as 0,
607   * the first is returned.
608   *
609   * <p><b>Implementation note:</b> this method is invoked by the default implementations of the
610   * other {@code min} overloads, so overriding it will affect their behavior.
611   *
612   * <p><b>Note:</b> Consider using {@code Comparators.min(a, b, thisComparator)} instead. If {@code
613   * thisComparator} is {@link Ordering#natural}, then use {@code Comparators.min(a, b)}.
614   *
615   * @param a value to compare, returned if less than or equal to b.
616   * @param b value to compare.
617   * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this
618   *     ordering.
619   */
620  @ParametricNullness
621  public <E extends T> E min(@ParametricNullness E a, @ParametricNullness E b) {
622    return (compare(a, b) <= 0) ? a : b;
623  }
624
625  /**
626   * Returns the least of the specified values according to this ordering. If there are multiple
627   * least values, the first of those is returned.
628   *
629   * <p><b>Java 8+ users:</b> Use {@code Collections.min(Arrays.asList(a, b, c...), thisComparator)}
630   * instead (but note that it does not guarantee which tied minimum element is returned).
631   *
632   * @param a value to compare, returned if less than or equal to the rest.
633   * @param b value to compare
634   * @param c value to compare
635   * @param rest values to compare
636   * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this
637   *     ordering.
638   */
639  @ParametricNullness
640  public <E extends T> E min(
641      @ParametricNullness E a, @ParametricNullness E b, @ParametricNullness E c, E... rest) {
642    E minSoFar = min(min(a, b), c);
643
644    for (E r : rest) {
645      minSoFar = min(minSoFar, r);
646    }
647
648    return minSoFar;
649  }
650
651  /**
652   * Returns the greatest of the specified values according to this ordering. If there are multiple
653   * greatest values, the first of those is returned. The iterator will be left exhausted: its
654   * {@code hasNext()} method will return {@code false}.
655   *
656   * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterator).max(thisComparator).get()} instead
657   * (but note that it does not guarantee which tied maximum element is returned).
658   *
659   * @param iterator the iterator whose maximum element is to be determined
660   * @throws NoSuchElementException if {@code iterator} is empty
661   * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this
662   *     ordering.
663   * @since 11.0
664   */
665  @ParametricNullness
666  public <E extends T> E max(Iterator<E> iterator) {
667    // let this throw NoSuchElementException as necessary
668    E maxSoFar = iterator.next();
669
670    while (iterator.hasNext()) {
671      maxSoFar = this.<E>max(maxSoFar, iterator.next());
672    }
673
674    return maxSoFar;
675  }
676
677  /**
678   * Returns the greatest of the specified values according to this ordering. If there are multiple
679   * greatest values, the first of those is returned.
680   *
681   * <p><b>Java 8+ users:</b> If {@code iterable} is a {@link Collection}, use {@code
682   * Collections.max(collection, thisComparator)} instead. Otherwise, use {@code
683   * Streams.stream(iterable).max(thisComparator).get()} instead. Note that these alternatives do
684   * not guarantee which tied maximum element is returned.
685   *
686   * @param iterable the iterable whose maximum element is to be determined
687   * @throws NoSuchElementException if {@code iterable} is empty
688   * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this
689   *     ordering.
690   */
691  @ParametricNullness
692  public <E extends T> E max(Iterable<E> iterable) {
693    return max(iterable.iterator());
694  }
695
696  /**
697   * Returns the greater of the two values according to this ordering. If the values compare as 0,
698   * the first is returned.
699   *
700   * <p><b>Implementation note:</b> this method is invoked by the default implementations of the
701   * other {@code max} overloads, so overriding it will affect their behavior.
702   *
703   * <p><b>Note:</b> Consider using {@code Comparators.max(a, b, thisComparator)} instead. If {@code
704   * thisComparator} is {@link Ordering#natural}, then use {@code Comparators.max(a, b)}.
705   *
706   * @param a value to compare, returned if greater than or equal to b.
707   * @param b value to compare.
708   * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this
709   *     ordering.
710   */
711  @ParametricNullness
712  public <E extends T> E max(@ParametricNullness E a, @ParametricNullness E b) {
713    return (compare(a, b) >= 0) ? a : b;
714  }
715
716  /**
717   * Returns the greatest of the specified values according to this ordering. If there are multiple
718   * greatest values, the first of those is returned.
719   *
720   * <p><b>Java 8+ users:</b> Use {@code Collections.max(Arrays.asList(a, b, c...), thisComparator)}
721   * instead (but note that it does not guarantee which tied maximum element is returned).
722   *
723   * @param a value to compare, returned if greater than or equal to the rest.
724   * @param b value to compare
725   * @param c value to compare
726   * @param rest values to compare
727   * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this
728   *     ordering.
729   */
730  @ParametricNullness
731  public <E extends T> E max(
732      @ParametricNullness E a, @ParametricNullness E b, @ParametricNullness E c, E... rest) {
733    E maxSoFar = max(max(a, b), c);
734
735    for (E r : rest) {
736      maxSoFar = max(maxSoFar, r);
737    }
738
739    return maxSoFar;
740  }
741
742  /**
743   * Returns the {@code k} least elements of the given iterable according to this ordering, in order
744   * from least to greatest. If there are fewer than {@code k} elements present, all will be
745   * included.
746   *
747   * <p>The implementation does not necessarily use a <i>stable</i> sorting algorithm; when multiple
748   * elements are equivalent, it is undefined which will come first.
749   *
750   * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterable).collect(Comparators.least(k,
751   * thisComparator))} instead.
752   *
753   * @return an immutable {@code RandomAccess} list of the {@code k} least elements in ascending
754   *     order
755   * @throws IllegalArgumentException if {@code k} is negative
756   * @since 8.0
757   */
758  public <E extends T> List<E> leastOf(Iterable<E> iterable, int k) {
759    if (iterable instanceof Collection) {
760      Collection<E> collection = (Collection<E>) iterable;
761      if (collection.size() <= 2L * k) {
762        // In this case, just dumping the collection to an array and sorting is
763        // faster than using the implementation for Iterator, which is
764        // specialized for k much smaller than n.
765
766        @SuppressWarnings("unchecked") // c only contains E's and doesn't escape
767        E[] array = (E[]) collection.toArray();
768        sort(array, this);
769        if (array.length > k) {
770          array = Arrays.copyOf(array, k);
771        }
772        return unmodifiableList(asList(array));
773      }
774    }
775    return leastOf(iterable.iterator(), k);
776  }
777
778  /**
779   * Returns the {@code k} least elements from the given iterator according to this ordering, in
780   * order from least to greatest. If there are fewer than {@code k} elements present, all will be
781   * included.
782   *
783   * <p>The implementation does not necessarily use a <i>stable</i> sorting algorithm; when multiple
784   * elements are equivalent, it is undefined which will come first.
785   *
786   * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterator).collect(Comparators.least(k,
787   * thisComparator))} instead.
788   *
789   * @return an immutable {@code RandomAccess} list of the {@code k} least elements in ascending
790   *     order
791   * @throws IllegalArgumentException if {@code k} is negative
792   * @since 14.0
793   */
794  public <E extends T> List<E> leastOf(Iterator<E> iterator, int k) {
795    checkNotNull(iterator);
796    checkNonnegative(k, "k");
797
798    if (k == 0 || !iterator.hasNext()) {
799      return emptyList();
800    } else if (k >= Integer.MAX_VALUE / 2) {
801      // k is really large; just do a straightforward sorted-copy-and-sublist
802      ArrayList<E> list = Lists.newArrayList(iterator);
803      sort(list, this);
804      if (list.size() > k) {
805        list.subList(k, list.size()).clear();
806      }
807      list.trimToSize();
808      return unmodifiableList(list);
809    } else {
810      TopKSelector<E> selector = TopKSelector.least(k, this);
811      selector.offerAll(iterator);
812      return selector.topK();
813    }
814  }
815
816  /**
817   * Returns the {@code k} greatest elements of the given iterable according to this ordering, in
818   * order from greatest to least. If there are fewer than {@code k} elements present, all will be
819   * included.
820   *
821   * <p>The implementation does not necessarily use a <i>stable</i> sorting algorithm; when multiple
822   * elements are equivalent, it is undefined which will come first.
823   *
824   * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterable).collect(Comparators.greatest(k,
825   * thisComparator))} instead.
826   *
827   * @return an immutable {@code RandomAccess} list of the {@code k} greatest elements in
828   *     <i>descending order</i>
829   * @throws IllegalArgumentException if {@code k} is negative
830   * @since 8.0
831   */
832  public <E extends T> List<E> greatestOf(Iterable<E> iterable, int k) {
833    // TODO(kevinb): see if delegation is hurting performance noticeably
834    // TODO(kevinb): if we change this implementation, add full unit tests.
835    return this.<E>reverse().leastOf(iterable, k);
836  }
837
838  /**
839   * Returns the {@code k} greatest elements from the given iterator according to this ordering, in
840   * order from greatest to least. If there are fewer than {@code k} elements present, all will be
841   * included.
842   *
843   * <p>The implementation does not necessarily use a <i>stable</i> sorting algorithm; when multiple
844   * elements are equivalent, it is undefined which will come first.
845   *
846   * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterator).collect(Comparators.greatest(k,
847   * thisComparator))} instead.
848   *
849   * @return an immutable {@code RandomAccess} list of the {@code k} greatest elements in
850   *     <i>descending order</i>
851   * @throws IllegalArgumentException if {@code k} is negative
852   * @since 14.0
853   */
854  public <E extends T> List<E> greatestOf(Iterator<E> iterator, int k) {
855    return this.<E>reverse().leastOf(iterator, k);
856  }
857
858  /**
859   * Returns a <b>mutable</b> list containing {@code elements} sorted by this ordering; use this
860   * only when the resulting list may need further modification, or may contain {@code null}. The
861   * input is not modified. The returned list is serializable and has random access.
862   *
863   * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard elements that are
864   * duplicates according to the comparator. The sort performed is <i>stable</i>, meaning that such
865   * elements will appear in the returned list in the same order they appeared in {@code elements}.
866   *
867   * <p><b>Performance note:</b> According to our
868   * benchmarking
869   * on Open JDK 7, {@link #immutableSortedCopy} generally performs better (in both time and space)
870   * than this method, and this method in turn generally performs better than copying the list and
871   * calling {@link Collections#sort(List)}.
872   */
873  // TODO(kevinb): rerun benchmarks including new options
874  public <E extends T> List<E> sortedCopy(Iterable<E> elements) {
875    @SuppressWarnings("unchecked") // does not escape, and contains only E's
876    E[] array = (E[]) Iterables.toArray(elements);
877    sort(array, this);
878    return Lists.newArrayList(asList(array));
879  }
880
881  /**
882   * Returns an <b>immutable</b> list containing {@code elements} sorted by this ordering. The input
883   * is not modified.
884   *
885   * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard elements that are
886   * duplicates according to the comparator. The sort performed is <i>stable</i>, meaning that such
887   * elements will appear in the returned list in the same order they appeared in {@code elements}.
888   *
889   * <p><b>Performance note:</b> According to our
890   * benchmarking
891   * on Open JDK 7, this method is the most efficient way to make a sorted copy of a collection.
892   *
893   * @throws NullPointerException if any element of {@code elements} is {@code null}
894   * @since 3.0
895   */
896  // TODO(kevinb): rerun benchmarks including new options
897  public <E extends @NonNull T> ImmutableList<E> immutableSortedCopy(Iterable<E> elements) {
898    return ImmutableList.sortedCopyOf(this, elements);
899  }
900
901  /**
902   * Returns {@code true} if each element in {@code iterable} after the first is greater than or
903   * equal to the element that preceded it, according to this ordering. Note that this is always
904   * true when the iterable has fewer than two elements.
905   *
906   * <p><b>Java 8+ users:</b> Use the equivalent {@link Comparators#isInOrder(Iterable, Comparator)}
907   * instead, since the rest of {@code Ordering} is mostly obsolete (as explained in the class
908   * documentation).
909   */
910  public boolean isOrdered(Iterable<? extends T> iterable) {
911    Iterator<? extends T> it = iterable.iterator();
912    if (it.hasNext()) {
913      T prev = it.next();
914      while (it.hasNext()) {
915        T next = it.next();
916        if (compare(prev, next) > 0) {
917          return false;
918        }
919        prev = next;
920      }
921    }
922    return true;
923  }
924
925  /**
926   * Returns {@code true} if each element in {@code iterable} after the first is <i>strictly</i>
927   * greater than the element that preceded it, according to this ordering. Note that this is always
928   * true when the iterable has fewer than two elements.
929   *
930   * <p><b>Java 8+ users:</b> Use the equivalent {@link Comparators#isInStrictOrder(Iterable,
931   * Comparator)} instead, since the rest of {@code Ordering} is mostly obsolete (as explained in
932   * the class documentation).
933   */
934  public boolean isStrictlyOrdered(Iterable<? extends T> iterable) {
935    Iterator<? extends T> it = iterable.iterator();
936    if (it.hasNext()) {
937      T prev = it.next();
938      while (it.hasNext()) {
939        T next = it.next();
940        if (compare(prev, next) >= 0) {
941          return false;
942        }
943        prev = next;
944      }
945    }
946    return true;
947  }
948
949  /**
950   * {@link Collections#binarySearch(List, Object, Comparator) Searches} {@code sortedList} for
951   * {@code key} using the binary search algorithm. The list must be sorted using this ordering.
952   *
953   * @param sortedList the list to be searched
954   * @param key the key to be searched for
955   * @deprecated Use {@link Collections#binarySearch(List, Object, Comparator)} directly.
956   */
957  @InlineMe(
958      replacement = "Collections.binarySearch(sortedList, key, this)",
959      imports = "java.util.Collections")
960  // We can't compatibly make this `final` now.
961  @InlineMeValidationDisabled(
962      "While binarySearch() is not final, the inlining is still safe as long as any overrides"
963          + " follow the contract.")
964  @Deprecated
965  public int binarySearch(
966      List<? extends T> sortedList, @ParametricNullness T key) {
967    return Collections.binarySearch(sortedList, key, this);
968  }
969
970  /**
971   * Exception thrown by a {@link Ordering#explicit(List)} or {@link Ordering#explicit(Object,
972   * Object[])} comparator when comparing a value outside the set of values it can compare.
973   * Extending {@link ClassCastException} may seem odd, but it is required.
974   */
975  static class IncomparableValueException extends ClassCastException {
976    final Object value;
977
978    IncomparableValueException(Object value) {
979      super("Cannot compare value: " + value);
980      this.value = value;
981    }
982
983    private static final long serialVersionUID = 0;
984  }
985
986  // Never make these public
987  static final int LEFT_IS_GREATER = 1;
988  static final int RIGHT_IS_GREATER = -1;
989}