- All Implemented Interfaces:
Comparator<T>
Comparator for pre-Java-8 users, in the same sense that FluentIterable is an
enriched Iterable for pre-Java-8 users.
Three types of methods
Like other fluent types, there are three types of methods present: methods for acquiring, chaining, and using.Acquiring
The common ways to get an instance of Ordering are:
- Subclass it and implement
compare(T, T)instead of implementingComparatordirectly - Pass a pre-existing
Comparatorinstance tofrom(Comparator) - Use the natural ordering,
natural()
Chaining
Then you can use the chaining methods to get an altered version of that
Ordering, including:
Using
Finally, use the resulting Ordering anywhere a Comparator is required, or use
any of its special operations, such as:
immutableSortedCopy(Iterable)isOrdered(Iterable)/isStrictlyOrdered(Iterable)min(Iterator)/max(Iterator)
Understanding complex orderings
Complex chained orderings like the following example can be challenging to understand.
Ordering<Foo> ordering =
Ordering.natural()
.nullsFirst()
.onResultOf(getBarFunction)
.nullsLast();
compare is called on the above ordering:
- First, if only one
Foois null, that null value is treated as greater - Next, non-null
Foovalues are passed togetBarFunction(we will be comparingBarvalues from now on) - Next, if only one
Baris null, that null value is treated as lesser - Finally, natural ordering is used (i.e. the result of
Bar.compareTo(Bar)is returned)
Alas, reverse() is a little different. As you read backwards through a chain and
encounter a call to reverse, continue working backwards until a result is determined, and
then reverse that result.
Additional notes
Except as noted, the orderings returned by the factory methods of this class are serializable
if and only if the provided instances that back them are. For example, if ordering and
function can themselves be serialized, then ordering.onResultOf(function) can as
well.
Java 8+ users
If you are using Java 8+, this class is now obsolete. Most of its functionality is now
provided by Stream and by Comparator itself, and the rest
can now be found as static methods in our new Comparators class. See each method below
for further instructions. Whenever possible, you should change any references of type
Ordering to be of type Comparator instead. However, at this time we have no plan to
deprecate this class.
Many replacements involve adopting Stream, and these changes can sometimes make your
code verbose. Whenever following this advice, you should check whether Stream could be
adopted more comprehensively in your code; the end result may be quite a bit simpler.
See also
See the Guava User Guide article on Ordering.
- Since:
- 2.0
- Author:
- Jesse Wilson, Kevin Bourrillion
-
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedOrdering()Constructs a new instance of this class (only invokable by the subclass constructor, typically implicit). -
Method Summary
Modifier and TypeMethodDescriptionallEqual()Returns an ordering which treats all values as equal, indicating "no ordering."Returns an arbitrary ordering over all objects, for whichcompare(a, b) == 0impliesa == b(identity equality).intbinarySearch(List<? extends T> sortedList, T key) Deprecated.abstract intcompound(Iterable<? extends Comparator<? super T>> comparators) Returns an ordering which tries each given comparator in order until a non-zero result is found, returning that result, and returning zero only if all comparators return zero.compound(Comparator<? super U> secondaryComparator) Returns an ordering which first uses the orderingthis, but which in the event of a "tie", then delegates tosecondaryComparator.static <T> Ordering<T> Returns an ordering that compares objects according to the order in which they appear in the given list.static <T> Ordering<T> explicit(T leastValue, T... remainingValuesInOrder) Returns an ordering that compares objects according to the order in which they are given to this method.Deprecated.no need to use thisfrom(Comparator<T> comparator) Returns an ordering based on an existing comparator instance.greatestOf(Iterable<E> iterable, int k) Returns thekgreatest elements of the given iterable according to this ordering, in order from greatest to least.greatestOf(Iterator<E> iterator, int k) Returns thekgreatest elements from the given iterator according to this ordering, in order from greatest to least.<E extends @NonNull T>
ImmutableList<E> immutableSortedCopy(Iterable<E> elements) Returns an immutable list containingelementssorted by this ordering.booleanReturnstrueif each element initerableafter the first is greater than or equal to the element that preceded it, according to this ordering.booleanisStrictlyOrdered(Iterable<? extends T> iterable) Returnstrueif each element initerableafter the first is strictly greater than the element that preceded it, according to this ordering.Returns thekleast elements of the given iterable according to this ordering, in order from least to greatest.Returns thekleast elements from the given iterator according to this ordering, in order from least to greatest.Returns a new ordering which sorts iterables by comparing corresponding elements pairwise until a nonzero result is found; imposes "dictionary order".<E extends T>
Emax(E a, E b) Returns the greater of the two values according to this ordering.<E extends T>
Emax(E a, E b, E c, E... rest) Returns the greatest of the specified values according to this ordering.<E extends T>
EReturns the greatest of the specified values according to this ordering.<E extends T>
EReturns the greatest of the specified values according to this ordering.<E extends T>
Emin(E a, E b) Returns the lesser of the two values according to this ordering.<E extends T>
Emin(E a, E b, E c, E... rest) Returns the least of the specified values according to this ordering.<E extends T>
EReturns the least of the specified values according to this ordering.<E extends T>
EReturns the least of the specified values according to this ordering.static <C extends Comparable>
Ordering<C> natural()Returns a serializable ordering that uses the natural order of the values.Returns an ordering that treatsnullas less than all other values and usesthisto compare non-null values.Returns an ordering that treatsnullas greater than all other values and uses this ordering to compare non-null values.onResultOf(Function<F, ? extends T> function) Returns a new ordering onFwhich orders elements by first applying a function to them, then comparing those results usingthis.reverse()Returns the reverse of this ordering; theOrderingequivalent toCollections.reverseOrder(Comparator).sortedCopy(Iterable<E> elements) Returns a mutable list containingelementssorted by this ordering; use this only when the resulting list may need further modification, or may containnull.Returns an ordering that compares objects by the natural ordering of their string representations as returned bytoString().Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface Comparator
equals, reversed, thenComparing, thenComparing, thenComparing, thenComparingDouble, thenComparingInt, thenComparingLong
-
Constructor Details
-
Ordering
protected Ordering()Constructs a new instance of this class (only invokable by the subclass constructor, typically implicit).
-
-
Method Details
-
natural
Returns a serializable ordering that uses the natural order of the values. The ordering throws aNullPointerExceptionwhen passed a null parameter.The type specification is
<C extends Comparable>, instead of the technically correct<C extends Comparable<? super C>>, to support legacy types from before Java 5.Java 8+ users: use
Comparator.naturalOrder()instead. -
from
Returns an ordering based on an existing comparator instance. Note that it is unnecessary to create a new anonymous inner class implementingComparatorjust to pass it in here. Instead, simply subclassOrderingand implement itscomparemethod directly.The returned object is serializable if
comparatoris serializable.Java 8+ users: this class is now obsolete as explained in the class documentation, so there is no need to use this method.
- Parameters:
comparator- the comparator that defines the order- Returns:
- comparator itself if it is already an
Ordering; otherwise an ordering that wraps that comparator
-
from
@InlineMe(replacement="checkNotNull(ordering)", staticImports="com.google.common.base.Preconditions.checkNotNull") @Deprecated public static <T extends @Nullable Object> Ordering<T> from(Ordering<T> ordering) Deprecated.no need to use thisSimply returns its argument. -
explicit
Returns an ordering that compares objects according to the order in which they appear in the given list. Only objects present in the list (according toObject.equals(Object)) may be compared. This comparator imposes a "partial ordering" over the typeT. Subsequent changes to thevaluesInOrderlist will have no effect on the returned comparator. Null values in the list are not supported.The returned comparator throws a
ClassCastExceptionwhen it receives an input parameter that isn't among the provided values.The generated comparator is serializable if all the provided values are serializable.
- Parameters:
valuesInOrder- the values that the returned comparator will be able to compare, in the order the comparator should induce- Returns:
- the comparator described above
- Throws:
NullPointerException- if any of the provided values is nullIllegalArgumentException- ifvaluesInOrdercontains any duplicate values (according toObject.equals(Object))
-
explicit
Returns an ordering that compares objects according to the order in which they are given to this method. Only objects present in the argument list (according toObject.equals(Object)) may be compared. This comparator imposes a "partial ordering" over the typeT. Null values in the argument list are not supported.The returned comparator throws a
ClassCastExceptionwhen it receives an input parameter that isn't among the provided values.The generated comparator is serializable if all the provided values are serializable.
- Parameters:
leastValue- the value which the returned comparator should consider the "least" of all valuesremainingValuesInOrder- the rest of the values that the returned comparator will be able to compare, in the order the comparator should follow- Returns:
- the comparator described above
- Throws:
NullPointerException- if any of the provided values is nullIllegalArgumentException- if any duplicate values (according toObject.equals(Object)) are present among the method arguments
-
allEqual
Returns an ordering which treats all values as equal, indicating "no ordering." Passing this ordering to any stable sort algorithm results in no change to the order of elements. Note especially thatsortedCopy(Iterable)andimmutableSortedCopy(Iterable)are stable, and in the returned instance these are implemented by simply copying the source list.Example:
Ordering.allEqual().nullsLast().sortedCopy( asList(t, null, e, s, null, t, null))Assuming
t,eandsare non-null, this returns[t, e, s, t, null, null, null]regardless of the true comparison order of those three values (which might not even implementComparableat all).Warning: by definition, this comparator is not consistent with equals (as defined here). Avoid its use in APIs, such as
TreeSet(Comparator), where such consistency is expected.The returned comparator is serializable.
Java 8+ users: Use the lambda expression
(a, b) -> 0instead (in certain cases you may need to cast that toComparator<YourType>).- Since:
- 13.0
-
usingToString
Returns an ordering that compares objects by the natural ordering of their string representations as returned bytoString(). It does not support null values.The comparator is serializable.
Java 8+ users: Use
Comparator.comparing(Object::toString)instead. -
arbitrary
Returns an arbitrary ordering over all objects, for whichcompare(a, b) == 0impliesa == b(identity equality). There is no meaning whatsoever to the order imposed, but it is constant for the life of the VM.Because the ordering is identity-based, it is not "consistent with
Object.equals(Object)" as defined byComparator. Use caution when building aSortedSetorSortedMapfrom it, as the resulting collection will not behave exactly according to spec.This ordering is not serializable, as its implementation relies on
System.identityHashCode(Object), so its behavior cannot be preserved across serialization.- Since:
- 2.0
-
reverse
Returns the reverse of this ordering; theOrderingequivalent toCollections.reverseOrder(Comparator).Java 8+ users: Use
thisComparator.reversed()instead. -
nullsFirst
-
nullsLast
Returns an ordering that treatsnullas greater than all other values and uses this ordering to compare non-null values.The returned object is serializable if this object is serializable.
Java 8+ users: Use
Comparator.nullsLast(thisComparator)instead. -
onResultOf
Returns a new ordering onFwhich orders elements by first applying a function to them, then comparing those results usingthis. For example, to compare objects by their string forms, in a case-insensitive manner, use:Ordering.from(String.CASE_INSENSITIVE_ORDER) .onResultOf(Functions.toStringFunction())Java 8+ users: Use
Comparator.comparing(function, thisComparator)instead (you can omit the comparator if it is the natural order). -
compound
Returns an ordering which first uses the orderingthis, but which in the event of a "tie", then delegates tosecondaryComparator. For example, to sort a bug list first by status and second by priority, you might usebyStatus.compound(byPriority). For a compound ordering with three or more components, simply chain multiple calls to this method.An ordering produced by this method, or a chain of calls to this method, is equivalent to one created using
compound(Iterable)on the same component comparators.The returned object is serializable if this object and
secondaryComparatorare both serializable.Java 8+ users: Use
thisComparator.thenComparing(secondaryComparator)instead. Depending on whatsecondaryComparatoris, one of the other overloads ofthenComparingmay be even more useful. -
compound
public static <T extends @Nullable Object> Ordering<T> compound(Iterable<? extends Comparator<? super T>> comparators) Returns an ordering which tries each given comparator in order until a non-zero result is found, returning that result, and returning zero only if all comparators return zero. The returned ordering is based on the state of thecomparatorsiterable at the time it was provided to this method.The returned ordering is equivalent to that produced using
Ordering.from(comp1).compound(comp2).compound(comp3) . . ..The returned object is serializable if each of the
comparatorsis serializable.Warning: Supplying an argument with undefined iteration order, such as a
HashSet, will produce non-deterministic results.Java 8+ users: Use a chain of calls to
Comparator.thenComparing(Comparator), orcomparatorCollection.stream().reduce(Comparator::thenComparing).get()(if the collection might be empty, also provide a default comparator as theidentityparameter toreduce).- Parameters:
comparators- the comparators to try in order
-
lexicographical
Returns a new ordering which sorts iterables by comparing corresponding elements pairwise until a nonzero result is found; imposes "dictionary order". If the end of one iterable is reached, but not the other, the shorter iterable is considered to be less than the longer one. For example, a lexicographical natural ordering over integers considers[] < [1] < [1, 1] < [1, 2] < [2].Note that
ordering.lexicographical().reverse()is not equivalent toordering.reverse().lexicographical()(consider how each would order[1]and[1, 1]).Java 8+ users: Use
Comparators.lexicographical(Comparator)instead.- Since:
- 2.0
-
compare
-
min
Returns the least of the specified values according to this ordering. If there are multiple least values, the first of those is returned. The iterator will be left exhausted: itshasNext()method will returnfalse.Java 8+ users: Use
Streams.stream(iterator).min(thisComparator).get()instead (but note that it does not guarantee which tied minimum element is returned).- Parameters:
iterator- the iterator whose minimum element is to be determined- Throws:
NoSuchElementException- ifiteratoris emptyClassCastException- if the parameters are not mutually comparable under this ordering.- Since:
- 11.0
-
min
Returns the least of the specified values according to this ordering. If there are multiple least values, the first of those is returned.Java 8+ users: If
iterableis aCollection, useCollections.min(collection, thisComparator)instead. Otherwise, useStreams.stream(iterable).min(thisComparator).get()instead. Note that these alternatives do not guarantee which tied minimum element is returned.- Parameters:
iterable- the iterable whose minimum element is to be determined- Throws:
NoSuchElementException- ifiterableis emptyClassCastException- if the parameters are not mutually comparable under this ordering.
-
min
Returns the lesser of the two values according to this ordering. If the values compare as 0, the first is returned.Implementation note: this method is invoked by the default implementations of the other
minoverloads, so overriding it will affect their behavior.Note: Consider using
Comparators.min(a, b, thisComparator)instead. IfthisComparatorisnatural(), then useComparators.min(a, b).- Parameters:
a- value to compare, returned if less than or equal to b.b- value to compare.- Throws:
ClassCastException- if the parameters are not mutually comparable under this ordering.
-
min
Returns the least of the specified values according to this ordering. If there are multiple least values, the first of those is returned.Java 8+ users: Use
Collections.min(Arrays.asList(a, b, c...), thisComparator)instead (but note that it does not guarantee which tied minimum element is returned).- Parameters:
a- value to compare, returned if less than or equal to the rest.b- value to comparec- value to comparerest- values to compare- Throws:
ClassCastException- if the parameters are not mutually comparable under this ordering.
-
max
Returns the greatest of the specified values according to this ordering. If there are multiple greatest values, the first of those is returned. The iterator will be left exhausted: itshasNext()method will returnfalse.Java 8+ users: Use
Streams.stream(iterator).max(thisComparator).get()instead (but note that it does not guarantee which tied maximum element is returned).- Parameters:
iterator- the iterator whose maximum element is to be determined- Throws:
NoSuchElementException- ifiteratoris emptyClassCastException- if the parameters are not mutually comparable under this ordering.- Since:
- 11.0
-
max
Returns the greatest of the specified values according to this ordering. If there are multiple greatest values, the first of those is returned.Java 8+ users: If
iterableis aCollection, useCollections.max(collection, thisComparator)instead. Otherwise, useStreams.stream(iterable).max(thisComparator).get()instead. Note that these alternatives do not guarantee which tied maximum element is returned.- Parameters:
iterable- the iterable whose maximum element is to be determined- Throws:
NoSuchElementException- ifiterableis emptyClassCastException- if the parameters are not mutually comparable under this ordering.
-
max
Returns the greater of the two values according to this ordering. If the values compare as 0, the first is returned.Implementation note: this method is invoked by the default implementations of the other
maxoverloads, so overriding it will affect their behavior.Note: Consider using
Comparators.max(a, b, thisComparator)instead. IfthisComparatorisnatural(), then useComparators.max(a, b).- Parameters:
a- value to compare, returned if greater than or equal to b.b- value to compare.- Throws:
ClassCastException- if the parameters are not mutually comparable under this ordering.
-
max
Returns the greatest of the specified values according to this ordering. If there are multiple greatest values, the first of those is returned.Java 8+ users: Use
Collections.max(Arrays.asList(a, b, c...), thisComparator)instead (but note that it does not guarantee which tied maximum element is returned).- Parameters:
a- value to compare, returned if greater than or equal to the rest.b- value to comparec- value to comparerest- values to compare- Throws:
ClassCastException- if the parameters are not mutually comparable under this ordering.
-
leastOf
Returns thekleast elements of the given iterable according to this ordering, in order from least to greatest. If there are fewer thankelements present, all will be included.The implementation does not necessarily use a stable sorting algorithm; when multiple elements are equivalent, it is undefined which will come first.
Java 8+ users: Use
Streams.stream(iterable).collect(Comparators.least(k, thisComparator))instead.- Returns:
- an immutable
RandomAccesslist of thekleast elements in ascending order - Throws:
IllegalArgumentException- ifkis negative- Since:
- 8.0
-
leastOf
Returns thekleast elements from the given iterator according to this ordering, in order from least to greatest. If there are fewer thankelements present, all will be included.The implementation does not necessarily use a stable sorting algorithm; when multiple elements are equivalent, it is undefined which will come first.
Java 8+ users: Use
Streams.stream(iterator).collect(Comparators.least(k, thisComparator))instead.- Returns:
- an immutable
RandomAccesslist of thekleast elements in ascending order - Throws:
IllegalArgumentException- ifkis negative- Since:
- 14.0
-
greatestOf
Returns thekgreatest elements of the given iterable according to this ordering, in order from greatest to least. If there are fewer thankelements present, all will be included.The implementation does not necessarily use a stable sorting algorithm; when multiple elements are equivalent, it is undefined which will come first.
Java 8+ users: Use
Streams.stream(iterable).collect(Comparators.greatest(k, thisComparator))instead.- Returns:
- an immutable
RandomAccesslist of thekgreatest elements in descending order - Throws:
IllegalArgumentException- ifkis negative- Since:
- 8.0
-
greatestOf
Returns thekgreatest elements from the given iterator according to this ordering, in order from greatest to least. If there are fewer thankelements present, all will be included.The implementation does not necessarily use a stable sorting algorithm; when multiple elements are equivalent, it is undefined which will come first.
Java 8+ users: Use
Streams.stream(iterator).collect(Comparators.greatest(k, thisComparator))instead.- Returns:
- an immutable
RandomAccesslist of thekgreatest elements in descending order - Throws:
IllegalArgumentException- ifkis negative- Since:
- 14.0
-
sortedCopy
Returns a mutable list containingelementssorted by this ordering; use this only when the resulting list may need further modification, or may containnull. The input is not modified. The returned list is serializable and has random access.Unlike
Sets.newTreeSet(Iterable), this method does not discard elements that are duplicates according to the comparator. The sort performed is stable, meaning that such elements will appear in the returned list in the same order they appeared inelements.Performance note: According to our benchmarking on Open JDK 7,
immutableSortedCopy(Iterable)generally performs better (in both time and space) than this method, and this method in turn generally performs better than copying the list and callingCollections.sort(List). -
immutableSortedCopy
Returns an immutable list containingelementssorted by this ordering. The input is not modified.Unlike
Sets.newTreeSet(Iterable), this method does not discard elements that are duplicates according to the comparator. The sort performed is stable, meaning that such elements will appear in the returned list in the same order they appeared inelements.Performance note: According to our benchmarking on Open JDK 7, this method is the most efficient way to make a sorted copy of a collection.
- Throws:
NullPointerException- if any element ofelementsisnull- Since:
- 3.0
-
isOrdered
Returnstrueif each element initerableafter the first is greater than or equal to the element that preceded it, according to this ordering. Note that this is always true when the iterable has fewer than two elements.Java 8+ users: Use the equivalent
Comparators.isInOrder(Iterable, Comparator)instead, since the rest ofOrderingis mostly obsolete (as explained in the class documentation). -
isStrictlyOrdered
Returnstrueif each element initerableafter the first is strictly greater than the element that preceded it, according to this ordering. Note that this is always true when the iterable has fewer than two elements.Java 8+ users: Use the equivalent
Comparators.isInStrictOrder(Iterable, Comparator)instead, since the rest ofOrderingis mostly obsolete (as explained in the class documentation). -
binarySearch
@InlineMe(replacement="Collections.binarySearch(sortedList, key, this)", imports="java.util.Collections") @Deprecated public int binarySearch(List<? extends T> sortedList, T key) Deprecated.UseCollections.binarySearch(List, Object, Comparator)directly.SearchessortedListforkeyusing the binary search algorithm. The list must be sorted using this ordering.- Parameters:
sortedList- the list to be searchedkey- the key to be searched for
-
Collections.binarySearch(List, Object, Comparator)directly.