Class Ordering<T>
- java.lang.Object
-
- com.google.common.collect.Ordering<T>
-
- All Implemented Interfaces:
java.util.Comparator<T>
@GwtCompatible public abstract class Ordering<T> extends java.lang.Object implements java.util.Comparator<T>
A comparator, with additional methods to support common operations. This is an "enriched" version ofComparator
, in the same sense thatFluentIterable
is an enrichedIterable
.The common ways to get an instance of
Ordering
are:- Subclass it and implement
compare(T, T)
instead of implementingComparator
directly - Pass a pre-existing
Comparator
instance tofrom(Comparator)
- Use the natural ordering,
natural()
Then you can use the chaining methods to get an altered version of that
Ordering
, including:Finally, use the resulting
Ordering
anywhere aComparator
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>)
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
andfunction
can themselves be serialized, thenordering.onResultOf(function)
can as well.See the Guava User Guide article on
Ordering
.- Since:
- 2.0 (imported from Google Collections Library)
-
-
Constructor Summary
Constructors Modifier Constructor Description protected
Ordering()
Constructs a new instance of this class (only invokable by the subclass constructor, typically implicit).
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static Ordering<java.lang.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.int
binarySearch(java.util.List<? extends T> sortedList, T key)
Searches
sortedList
forkey
using the binary search algorithm.abstract int
compare(T left, T right)
static <T> Ordering<T>
compound(java.lang.Iterable<? extends java.util.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.<U extends T>
Ordering<U>compound(java.util.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>
explicit(java.util.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(Ordering<T> ordering)
Deprecated.no need to use thisstatic <T> Ordering<T>
from(java.util.Comparator<T> comparator)
Returns an ordering based on an existing comparator instance.<E extends T>
java.util.List<E>greatestOf(java.lang.Iterable<E> iterable, int k)
Returns thek
greatest elements of the given iterable according to this ordering, in order from greatest to least.<E extends T>
java.util.List<E>greatestOf(java.util.Iterator<E> iterator, int k)
Returns thek
greatest elements from the given iterator according to this ordering, in order from greatest to least.<E extends T>
ImmutableList<E>immutableSortedCopy(java.lang.Iterable<E> elements)
Returns an immutable list containingelements
sorted by this ordering.boolean
isOrdered(java.lang.Iterable<? extends T> iterable)
Returnstrue
if each element initerable
after the first is greater than or equal to the element that preceded it, according to this ordering.boolean
isStrictlyOrdered(java.lang.Iterable<? extends T> iterable)
Returnstrue
if each element initerable
after the first is strictly greater than the element that preceded it, according to this ordering.<E extends T>
java.util.List<E>leastOf(java.lang.Iterable<E> iterable, int k)
Returns thek
least elements of the given iterable according to this ordering, in order from least to greatest.<E extends T>
java.util.List<E>leastOf(java.util.Iterator<E> elements, int k)
Returns thek
least elements from the given iterator according to this ordering, in order from least to greatest.<S extends T>
Ordering<java.lang.Iterable<S>>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>
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>
Emax(java.lang.Iterable<E> iterable)
Returns the greatest of the specified values according to this ordering.<E extends T>
Emax(java.util.Iterator<E> iterator)
Returns 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>
Emin(java.lang.Iterable<E> iterable)
Returns the least of the specified values according to this ordering.<E extends T>
Emin(java.util.Iterator<E> iterator)
Returns the least of the specified values according to this ordering.static <C extends java.lang.Comparable>
Ordering<C>natural()
Returns a serializable ordering that uses the natural order of the values.<S extends T>
Ordering<S>nullsFirst()
Returns an ordering that treatsnull
as less than all other values and usesthis
to compare non-null values.<S extends T>
Ordering<S>nullsLast()
Returns an ordering that treatsnull
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 onF
which orders elements by first applying a function to them, then comparing those results usingthis
.<S extends T>
Ordering<S>reverse()
Returns the reverse of this ordering; theOrdering
equivalent toCollections.reverseOrder(Comparator)
.<E extends T>
java.util.List<E>sortedCopy(java.lang.Iterable<E> elements)
Returns a mutable list containingelements
sorted by this ordering; use this only when the resulting list may need further modification, or may containnull
.static Ordering<java.lang.Object>
usingToString()
Returns an ordering that compares objects by the natural ordering of their string representations as returned bytoString()
.
-
-
-
Method Detail
-
natural
@GwtCompatible(serializable=true) public static <C extends java.lang.Comparable> Ordering<C> natural()
Returns a serializable ordering that uses the natural order of the values. The ordering throws aNullPointerException
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.
-
from
@GwtCompatible(serializable=true) public static <T> Ordering<T> from(java.util.Comparator<T> comparator)
Returns an ordering based on an existing comparator instance. Note that it is unnecessary to create a new anonymous inner class implementingComparator
just to pass it in here. Instead, simply subclassOrdering
and implement itscompare
method directly.- 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
@GwtCompatible(serializable=true) @Deprecated public static <T> Ordering<T> from(Ordering<T> ordering)
Deprecated.no need to use thisSimply returns its argument.
-
explicit
@GwtCompatible(serializable=true) public static <T> Ordering<T> explicit(java.util.List<T> valuesInOrder)
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(java.lang.Object)
) may be compared. This comparator imposes a "partial ordering" over the typeT
. Subsequent changes to thevaluesInOrder
list will have no effect on the returned comparator. Null values in the list are not supported.The returned comparator throws an
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.
- 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:
java.lang.NullPointerException
- if any of the provided values is nulljava.lang.IllegalArgumentException
- ifvaluesInOrder
contains any duplicate values (according toObject.equals(java.lang.Object)
)
-
explicit
@GwtCompatible(serializable=true) public 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. Only objects present in the argument list (according toObject.equals(java.lang.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
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.
- 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:
java.lang.NullPointerException
- if any of the provided values is nulljava.lang.IllegalArgumentException
- if any duplicate values (according toObject.equals(Object)
) are present among the method arguments
-
allEqual
@GwtCompatible(serializable=true) public static Ordering<java.lang.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. Note especially thatsortedCopy(java.lang.Iterable<E>)
andimmutableSortedCopy(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
ands
are non-null, this returns[t, e, s, t, null, null, null]
regardlesss of the true comparison order of those three values (which might not even implementComparable
at 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.
-
usingToString
@GwtCompatible(serializable=true) public static Ordering<java.lang.Object> 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.
-
reverse
@GwtCompatible(serializable=true) public <S extends T> Ordering<S> reverse()
Returns the reverse of this ordering; theOrdering
equivalent toCollections.reverseOrder(Comparator)
.
-
nullsFirst
@GwtCompatible(serializable=true) public <S extends T> Ordering<S> nullsFirst()
Returns an ordering that treatsnull
as less than all other values and usesthis
to compare non-null values.
-
nullsLast
@GwtCompatible(serializable=true) public <S extends T> Ordering<S> nullsLast()
Returns an ordering that treatsnull
as greater than all other values and uses this ordering to compare non-null values.
-
onResultOf
@GwtCompatible(serializable=true) public <F> Ordering<F> onResultOf(Function<F,? extends T> function)
Returns a new ordering onF
which 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())
-
compound
@GwtCompatible(serializable=true) public <U extends T> Ordering<U> compound(java.util.Comparator<? super U> secondaryComparator)
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.
-
compound
@GwtCompatible(serializable=true) public static <T> Ordering<T> compound(java.lang.Iterable<? extends java.util.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 thecomparators
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.- Parameters:
comparators
- the comparators to try in order
-
lexicographical
@GwtCompatible(serializable=true) public <S extends T> Ordering<java.lang.Iterable<S>> 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]
).- Since:
- 2.0
-
compare
public abstract int compare(@Nullable T left, @Nullable T right)
- Specified by:
compare
in interfacejava.util.Comparator<T>
-
min
public <E extends T> E min(java.util.Iterator<E> iterator)
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
.- Parameters:
iterator
- the iterator whose minimum element is to be determined- Throws:
java.util.NoSuchElementException
- ifiterator
is emptyjava.lang.ClassCastException
- if the parameters are not mutually comparable under this ordering.- Since:
- 11.0
-
min
public <E extends T> E min(java.lang.Iterable<E> iterable)
Returns the least of the specified values according to this ordering. If there are multiple least values, the first of those is returned.- Parameters:
iterable
- the iterable whose minimum element is to be determined- Throws:
java.util.NoSuchElementException
- ifiterable
is emptyjava.lang.ClassCastException
- if the parameters are not mutually comparable under this ordering.
-
min
public <E extends T> E min(@Nullable E a, @Nullable E b)
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
min
overloads, so overriding it will affect their behavior.- Parameters:
a
- value to compare, returned if less than or equal to b.b
- value to compare.- Throws:
java.lang.ClassCastException
- if the parameters are not mutually comparable under this ordering.
-
min
public <E extends T> E min(@Nullable E a, @Nullable E b, @Nullable E c, E... rest)
Returns the least of the specified values according to this ordering. If there are multiple least values, the first of those 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:
java.lang.ClassCastException
- if the parameters are not mutually comparable under this ordering.
-
max
public <E extends T> E max(java.util.Iterator<E> iterator)
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
.- Parameters:
iterator
- the iterator whose maximum element is to be determined- Throws:
java.util.NoSuchElementException
- ifiterator
is emptyjava.lang.ClassCastException
- if the parameters are not mutually comparable under this ordering.- Since:
- 11.0
-
max
public <E extends T> E max(java.lang.Iterable<E> iterable)
Returns the greatest of the specified values according to this ordering. If there are multiple greatest values, the first of those is returned.- Parameters:
iterable
- the iterable whose maximum element is to be determined- Throws:
java.util.NoSuchElementException
- ifiterable
is emptyjava.lang.ClassCastException
- if the parameters are not mutually comparable under this ordering.
-
max
public <E extends T> E max(@Nullable E a, @Nullable E b)
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
max
overloads, so overriding it will affect their behavior.- Parameters:
a
- value to compare, returned if greater than or equal to b.b
- value to compare.- Throws:
java.lang.ClassCastException
- if the parameters are not mutually comparable under this ordering.
-
max
public <E extends T> E max(@Nullable E a, @Nullable E b, @Nullable E c, E... rest)
Returns the greatest of the specified values according to this ordering. If there are multiple greatest values, the first of those 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:
java.lang.ClassCastException
- if the parameters are not mutually comparable under this ordering.
-
leastOf
public <E extends T> java.util.List<E> leastOf(java.lang.Iterable<E> iterable, int k)
Returns thek
least elements of the given iterable according to this ordering, in order from least to greatest. If there are fewer thank
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.
- Returns:
- an immutable
RandomAccess
list of thek
least elements in ascending order - Throws:
java.lang.IllegalArgumentException
- ifk
is negative- Since:
- 8.0
-
leastOf
public <E extends T> java.util.List<E> leastOf(java.util.Iterator<E> elements, int k)
Returns thek
least elements from the given iterator according to this ordering, in order from least to greatest. If there are fewer thank
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.
- Returns:
- an immutable
RandomAccess
list of thek
least elements in ascending order - Throws:
java.lang.IllegalArgumentException
- ifk
is negative- Since:
- 14.0
-
greatestOf
public <E extends T> java.util.List<E> greatestOf(java.lang.Iterable<E> iterable, int k)
Returns thek
greatest elements of the given iterable according to this ordering, in order from greatest to least. If there are fewer thank
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.
- Returns:
- an immutable
RandomAccess
list of thek
greatest elements in descending order - Throws:
java.lang.IllegalArgumentException
- ifk
is negative- Since:
- 8.0
-
greatestOf
public <E extends T> java.util.List<E> greatestOf(java.util.Iterator<E> iterator, int k)
Returns thek
greatest elements from the given iterator according to this ordering, in order from greatest to least. If there are fewer thank
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.
- Returns:
- an immutable
RandomAccess
list of thek
greatest elements in descending order - Throws:
java.lang.IllegalArgumentException
- ifk
is negative- Since:
- 14.0
-
sortedCopy
public <E extends T> java.util.List<E> sortedCopy(java.lang.Iterable<E> elements)
Returns a mutable list containingelements
sorted 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(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 callingCollections.sort(List)
.
-
immutableSortedCopy
public <E extends T> ImmutableList<E> immutableSortedCopy(java.lang.Iterable<E> elements)
Returns an immutable list containingelements
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 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:
java.lang.NullPointerException
- if any ofelements
(orelements
itself) is null- Since:
- 3.0
-
isOrdered
public boolean isOrdered(java.lang.Iterable<? extends T> iterable)
Returnstrue
if each element initerable
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.
-
isStrictlyOrdered
public boolean isStrictlyOrdered(java.lang.Iterable<? extends T> iterable)
Returnstrue
if each element initerable
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.
-
-