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