@GwtCompatible public abstract class Ordering<T> extends Object implements Comparator<T>
Comparator
for pre-Java-8 users, in the same sense that FluentIterable
is an
enriched Iterable
for pre-Java-8 users.
The common ways to get an instance of Ordering
are:
compare(T, T)
instead of implementing Comparator
directly
Comparator
instance to from(Comparator)
natural()
Then you can use the chaining methods to get an altered version of that Ordering
, including:
Finally, use the resulting Ordering
anywhere a Comparator
is required, or use
any of its special operations, such as:
immutableSortedCopy(java.lang.Iterable<E>)
isOrdered(java.lang.Iterable<? extends T>)
/ isStrictlyOrdered(java.lang.Iterable<? extends T>)
min(java.util.Iterator<E>)
/ max(java.util.Iterator<E>)
Complex chained orderings like the following example can be challenging to understand.
Ordering<Foo> ordering =
Ordering.natural()
.nullsFirst()
.onResultOf(getBarFunction)
.nullsLast();
Note that each chaining method returns a new ordering instance which is backed by the previous
instance, but has the chance to act on values before handing off to that backing instance.
As a result, it usually helps to read chained ordering expressions backwards. For example,
when compare
is called on the above ordering:
Foo
is null, that null value is treated as greater
Foo
values are passed to getBarFunction
(we will be
comparing Bar
values from now on)
Bar
is null, that null value is treated as lesser
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.
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.
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 the Guava User Guide article on Ordering
.
Modifier | Constructor and Description |
---|---|
protected |
Ordering()
Constructs a new instance of this class (only invokable by the subclass constructor, typically
implicit).
|
Modifier and Type | Method and Description |
---|---|
static Ordering<Object> |
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.
|
static Ordering<Object> |
arbitrary()
Returns an arbitrary ordering over all objects, for which
compare(a, b) == 0 implies
a == b (identity equality). |
int |
binarySearch(List<? extends T> sortedList,
T key)
Deprecated.
Use
Collections.binarySearch(List, Object, Comparator) directly. |
abstract int |
compare(T left,
T right)
Compares its two arguments for order.
|
<U extends T> |
compound(Comparator<? super U> secondaryComparator)
Returns an ordering which first uses the ordering
this , but which in the event of a
"tie", then delegates to secondaryComparator . |
static <T> 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.
|
static <T> Ordering<T> |
explicit(List<T> valuesInOrder)
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.
|
static <T> Ordering<T> |
from(Comparator<T> comparator)
Returns an ordering based on an existing comparator instance.
|
static <T> Ordering<T> |
from(Ordering<T> ordering)
Deprecated.
no need to use this
|
<E extends T> |
greatestOf(Iterable<E> iterable,
int k)
Returns the
k greatest elements of the given iterable according to this ordering, in
order from greatest to least. |
<E extends T> |
greatestOf(Iterator<E> iterator,
int k)
Returns the
k greatest elements from the given iterator according to this ordering, in
order from greatest to least. |
<E extends T> |
immutableSortedCopy(Iterable<E> elements)
Returns an immutable list containing
elements sorted by this ordering. |
boolean |
isOrdered(Iterable<? extends T> iterable)
Returns
true if each element in iterable after the first is greater than or
equal to the element that preceded it, according to this ordering. |
boolean |
isStrictlyOrdered(Iterable<? extends T> iterable)
Returns
true if each element in iterable after the first is strictly
greater than the element that preceded it, according to this ordering. |
<E extends T> |
leastOf(Iterable<E> iterable,
int k)
Returns the
k least elements of the given iterable according to this ordering, in order
from least to greatest. |
<E extends T> |
leastOf(Iterator<E> iterator,
int k)
Returns the
k least elements from the given iterator according to this ordering, in
order from least to greatest. |
<S extends T> |
lexicographical()
Returns a new ordering which sorts iterables by comparing corresponding elements pairwise until
a nonzero result is found; imposes "dictionary order".
|
<E extends T> |
max(E a,
E b)
Returns the greater of the two values according to this ordering.
|
<E extends T> |
max(E a,
E b,
E c,
E... rest)
Returns the greatest of the specified values according to this ordering.
|
<E extends T> |
max(Iterable<E> iterable)
Returns the greatest of the specified values according to this ordering.
|
<E extends T> |
max(Iterator<E> iterator)
Returns the greatest of the specified values according to this ordering.
|
<E extends T> |
min(E a,
E b)
Returns the lesser of the two values according to this ordering.
|
<E extends T> |
min(E a,
E b,
E c,
E... rest)
Returns the least of the specified values according to this ordering.
|
<E extends T> |
min(Iterable<E> iterable)
Returns the least of the specified values according to this ordering.
|
<E extends T> |
min(Iterator<E> iterator)
Returns the least of the specified values according to this ordering.
|
static <C extends Comparable> |
natural()
Returns a serializable ordering that uses the natural order of the values.
|
<S extends T> |
nullsFirst()
Returns an ordering that treats
null as less than all other values and uses this to compare non-null values. |
<S extends T> |
nullsLast()
Returns an ordering that treats
null as greater than all other values and uses this
ordering to compare non-null values. |
<F> Ordering<F> |
onResultOf(Function<F,? extends T> function)
Returns a new ordering on
F which orders elements by first applying a function to them,
then comparing those results using this . |
<S extends T> |
reverse()
Returns the reverse of this ordering; the
Ordering equivalent to Collections.reverseOrder(Comparator) . |
<E extends T> |
sortedCopy(Iterable<E> elements)
Returns a mutable list containing
elements sorted by this ordering; use this
only when the resulting list may need further modification, or may contain null . |
static Ordering<Object> |
usingToString()
Returns an ordering that compares objects by the natural ordering of their string
representations as returned by
toString() . |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
comparing, comparing, comparingDouble, comparingInt, comparingLong, equals, naturalOrder, nullsFirst, nullsLast, reversed, reverseOrder, thenComparing, thenComparing, thenComparing, thenComparingDouble, thenComparingInt, thenComparingLong
protected Ordering()
@GwtCompatible(serializable=true) public static <C extends Comparable> Ordering<C> natural()
NullPointerException
when 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.
@GwtCompatible(serializable=true) public static <T> Ordering<T> from(Comparator<T> comparator)
Comparator
just
to pass it in here. Instead, simply subclass Ordering
and implement its compare
method directly.
Java 8 users: this class is now obsolete as explained in the class documentation, so there is no need to use this method.
comparator
- the comparator that defines the orderOrdering
; otherwise an ordering that
wraps that comparator@GwtCompatible(serializable=true) @Deprecated public static <T> Ordering<T> from(Ordering<T> ordering)
@GwtCompatible(serializable=true) public static <T> Ordering<T> explicit(List<T> valuesInOrder)
Object.equals(java.lang.Object)
) may be
compared. This comparator imposes a "partial ordering" over the type T
. Subsequent
changes to the valuesInOrder
list will have no effect on the returned comparator. Null
values in the list are not supported.
The returned comparator throws a ClassCastException
when it receives an input
parameter that isn't among the provided values.
The generated comparator is serializable if all the provided values are serializable.
valuesInOrder
- the values that the returned comparator will be able to compare, in the
order the comparator should induceNullPointerException
- if any of the provided values is nullIllegalArgumentException
- if valuesInOrder
contains any duplicate values
(according to Object.equals(java.lang.Object)
)@GwtCompatible(serializable=true) public static <T> Ordering<T> explicit(T leastValue, T... remainingValuesInOrder)
Object.equals(java.lang.Object)
) may
be compared. This comparator imposes a "partial ordering" over the type T
. Null values
in the argument list are not supported.
The returned comparator throws a ClassCastException
when it receives an input
parameter that isn't among the provided values.
The generated comparator is serializable if all the provided values are serializable.
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 followNullPointerException
- if any of the provided values is nullIllegalArgumentException
- if any duplicate values (according to Object.equals(Object)
) are present among the method arguments@GwtCompatible(serializable=true) public static Ordering<Object> allEqual()
sortedCopy(java.lang.Iterable<E>)
and immutableSortedCopy(java.lang.Iterable<E>)
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
, e
and s
are 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 implement Comparable
at all).
Warning: by definition, this comparator is not consistent with equals (as
defined here). Avoid its use in APIs, such as TreeSet#TreeSet(Comparator)
, where such consistency is expected.
The returned comparator is serializable.
Java 8 users: Use the lambda expression (a, b) -> 0
instead (in certain cases
you may need to cast that to Comparator<YourType>
).
@GwtCompatible(serializable=true) public static Ordering<Object> usingToString()
toString()
. It does not support null values.
The comparator is serializable.
Java 8 users: Use Comparator.comparing(Object::toString)
instead.
public static Ordering<Object> arbitrary()
compare(a, b) == 0
implies
a == 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 by Comparator
. Use caution when building a SortedSet
or SortedMap
from 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.
@GwtCompatible(serializable=true) public <S extends T> Ordering<S> reverse()
Ordering
equivalent to Collections.reverseOrder(Comparator)
.
Java 8 users: Use thisComparator.reversed()
instead.
@GwtCompatible(serializable=true) public <S extends T> Ordering<S> nullsFirst()
null
as less than all other values and uses this
to compare non-null values.
Java 8 users: Use Comparator.nullsFirst(thisComparator)
instead.
@GwtCompatible(serializable=true) public <S extends T> Ordering<S> nullsLast()
null
as greater than all other values and uses this
ordering to compare non-null values.
Java 8 users: Use Comparator.nullsLast(thisComparator)
instead.
@GwtCompatible(serializable=true) public <F> Ordering<F> onResultOf(Function<F,? extends T> function)
F
which orders elements by first applying a function to them,
then comparing those results using this
. 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).
@GwtCompatible(serializable=true) public <U extends T> Ordering<U> compound(Comparator<? super U> secondaryComparator)
this
, but which in the event of a
"tie", then delegates to secondaryComparator
. For example, to sort a bug list first by
status and second by priority, you might use byStatus.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.
Java 8 users: Use thisComparator.thenComparing(secondaryComparator)
instead.
Depending on what secondaryComparator
is, one of the other overloads of thenComparing
may be even more useful.
@GwtCompatible(serializable=true) public static <T> Ordering<T> compound(Iterable<? extends Comparator<? super T>> comparators)
comparators
iterable 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) . . .
.
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)
,
or comparatorCollection.stream().reduce(Comparator::thenComparing).get()
(if the
collection might be empty, also provide a default comparator as the identity
parameter
to reduce
).
comparators
- the comparators to try in order@GwtCompatible(serializable=true) public <S extends T> Ordering<Iterable<S>> lexicographical()
[] < [1] < [1, 1] <
[1, 2] < [2]
.
Note that ordering.lexicographical().reverse()
is not equivalent to ordering.reverse().lexicographical()
(consider how each would order [1]
and [1,
1]
).
Java 8 users: Use Comparators.lexicographical(Comparator)
instead.
@CanIgnoreReturnValue public abstract int compare(@NullableDecl T left, @NullableDecl T right)
java.util.Comparator
In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.
The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)
The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.
Finally, the implementor must ensure that compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.
It is generally the case, but not strictly required that (compare(x, y)==0) == (x.equals(y)). Generally speaking, any comparator that violates this condition should clearly indicate this fact. The recommended language is "Note: this comparator imposes orderings that are inconsistent with equals."
compare
in interface Comparator<T>
left
- the first object to be compared.right
- the second object to be compared.public <E extends T> E min(Iterator<E> iterator)
hasNext()
method will return false
.
Java 8 users: Continue to use this method for now. After the next release of Guava,
use Streams.stream(iterator).min(thisComparator).get()
instead (but note that it does
not guarantee which tied minimum element is returned).
iterator
- the iterator whose minimum element is to be determinedNoSuchElementException
- if iterator
is emptyClassCastException
- if the parameters are not mutually comparable under this
ordering.public <E extends T> E min(Iterable<E> iterable)
Java 8 users: If iterable
is a Collection
, use Collections.min(collection, thisComparator)
instead. Otherwise, continue to use this method
for now. After the next release of Guava, use Streams.stream(iterable).min(thisComparator).get()
instead. Note that these alternatives do
not guarantee which tied minimum element is returned)
iterable
- the iterable whose minimum element is to be determinedNoSuchElementException
- if iterable
is emptyClassCastException
- if the parameters are not mutually comparable under this
ordering.public <E extends T> E min(@NullableDecl E a, @NullableDecl E b)
Implementation note: this method is invoked by the default implementations of the
other min
overloads, so overriding it will affect their behavior.
Java 8 users: Use Collections.min(Arrays.asList(a, b), thisComparator)
instead (but note that it does not guarantee which tied minimum element is returned).
a
- value to compare, returned if less than or equal to b.b
- value to compare.ClassCastException
- if the parameters are not mutually comparable under this
ordering.public <E extends T> E min(@NullableDecl E a, @NullableDecl E b, @NullableDecl E c, E... rest)
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).
a
- value to compare, returned if less than or equal to the rest.b
- value to comparec
- value to comparerest
- values to compareClassCastException
- if the parameters are not mutually comparable under this
ordering.public <E extends T> E max(Iterator<E> iterator)
hasNext()
method will return false
.
Java 8 users: Continue to use this method for now. After the next release of Guava,
use Streams.stream(iterator).max(thisComparator).get()
instead (but note that it does
not guarantee which tied maximum element is returned).
iterator
- the iterator whose maximum element is to be determinedNoSuchElementException
- if iterator
is emptyClassCastException
- if the parameters are not mutually comparable under this
ordering.public <E extends T> E max(Iterable<E> iterable)
Java 8 users: If iterable
is a Collection
, use Collections.max(collection, thisComparator)
instead. Otherwise, continue to use this method
for now. After the next release of Guava, use Streams.stream(iterable).max(thisComparator).get()
instead. Note that these alternatives do
not guarantee which tied maximum element is returned)
iterable
- the iterable whose maximum element is to be determinedNoSuchElementException
- if iterable
is emptyClassCastException
- if the parameters are not mutually comparable under this
ordering.public <E extends T> E max(@NullableDecl E a, @NullableDecl E b)
Implementation note: this method is invoked by the default implementations of the
other max
overloads, so overriding it will affect their behavior.
Java 8 users: Use Collections.max(Arrays.asList(a, b), thisComparator)
instead (but note that it does not guarantee which tied maximum element is returned).
a
- value to compare, returned if greater than or equal to b.b
- value to compare.ClassCastException
- if the parameters are not mutually comparable under this
ordering.public <E extends T> E max(@NullableDecl E a, @NullableDecl E b, @NullableDecl E c, E... rest)
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).
a
- value to compare, returned if greater than or equal to the rest.b
- value to comparec
- value to comparerest
- values to compareClassCastException
- if the parameters are not mutually comparable under this
ordering.public <E extends T> List<E> leastOf(Iterable<E> iterable, int k)
k
least elements of the given iterable according to this ordering, in order
from least to greatest. If there are fewer than k
elements 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: Continue to use this method for now. After the next release of Guava,
use Streams.stream(iterable).collect(Comparators.least(k, thisComparator))
instead.
RandomAccess
list of the k
least elements in ascending
orderIllegalArgumentException
- if k
is negativepublic <E extends T> List<E> leastOf(Iterator<E> iterator, int k)
k
least elements from the given iterator according to this ordering, in
order from least to greatest. If there are fewer than k
elements 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: Continue to use this method for now. After the next release of Guava,
use Streams.stream(iterator).collect(Comparators.least(k, thisComparator))
instead.
RandomAccess
list of the k
least elements in ascending
orderIllegalArgumentException
- if k
is negativepublic <E extends T> List<E> greatestOf(Iterable<E> iterable, int k)
k
greatest elements of the given iterable according to this ordering, in
order from greatest to least. If there are fewer than k
elements 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: Continue to use this method for now. After the next release of Guava,
use Streams.stream(iterable).collect(Comparators.greatest(k, thisComparator))
instead.
RandomAccess
list of the k
greatest elements in
descending orderIllegalArgumentException
- if k
is negativepublic <E extends T> List<E> greatestOf(Iterator<E> iterator, int k)
k
greatest elements from the given iterator according to this ordering, in
order from greatest to least. If there are fewer than k
elements 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: Continue to use this method for now. After the next release of Guava,
use Streams.stream(iterator).collect(Comparators.greatest(k, thisComparator))
instead.
RandomAccess
list of the k
greatest elements in
descending orderIllegalArgumentException
- if k
is negativepublic <E extends T> List<E> sortedCopy(Iterable<E> elements)
elements
sorted by this ordering; use this
only when the resulting list may need further modification, or may contain null
. 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 in elements
.
Performance note: According to our
benchmarking
on Open JDK 7, immutableSortedCopy(java.lang.Iterable<E>)
generally performs better (in both time and space)
than this method, and this method in turn generally performs better than copying the list and
calling Collections.sort(List)
.
public <E extends T> ImmutableList<E> immutableSortedCopy(Iterable<E> elements)
elements
sorted 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 in elements
.
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.
NullPointerException
- if any element of elements
is null
public boolean isOrdered(Iterable<? extends T> iterable)
true
if each element in iterable
after 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 of Ordering
is mostly obsolete (as explained in the class
documentation).
public boolean isStrictlyOrdered(Iterable<? extends T> iterable)
true
if each element in iterable
after 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 of Ordering
is mostly obsolete (as explained in
the class documentation).
@Deprecated public int binarySearch(List<? extends T> sortedList, @NullableDecl T key)
Collections.binarySearch(List, Object, Comparator)
directly.Searches
sortedList
for
key
using the binary search algorithm. The list must be sorted using this ordering.sortedList
- the list to be searchedkey
- the key to be searched forCopyright © 2010–2019. All rights reserved.