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