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