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