Top Description Inners Fields Constructors Methods
com.google.common.collect

public abstract Class Ordering<T extends @Nullable Object>

extends Object
implements Comparator<T extends @Nullable Object>
Class Inheritance
All Implemented Interfaces
java.util.Comparator
Known Direct Subclasses
com.google.common.collect.Ordering.ArbitraryOrdering, com.google.common.collect.Range.RangeLexOrdering, com.google.common.collect.ReverseNaturalOrdering, com.google.common.collect.ReverseOrdering, com.google.common.collect.UsingToStringOrdering, com.google.common.collect.AllEqualOrdering, com.google.common.collect.ByFunctionOrdering, com.google.common.collect.ComparatorOrdering, com.google.common.collect.CompoundOrdering, com.google.common.collect.ExplicitOrdering, com.google.common.collect.LexicographicalOrdering, com.google.common.collect.NaturalOrdering, com.google.common.collect.NullsFirstOrdering, com.google.common.collect.NullsLastOrdering
Annotations
@GwtCompatible
@ElementTypesAreNonnullByDefault
Static Imports
com.google.common.base.Preconditions.checkNotNull, com.google.common.collect.CollectPreconditions.checkNonnegative

A comparator, with additional methods to support common operations. This is an "enriched" version of 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:

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:

Understanding complex orderings

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:
  1. First, if only one Foo is null, that null value is treated as greater
  2. Next, non-null Foo values are passed to getBarFunction (we will be comparing Bar values from now on)
  3. Next, if only one Bar is null, that null value is treated as lesser
  4. 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.

For 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.

Authors
Jesse Wilson, Kevin Bourrillion
Since
2.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static class
private static class
pack-priv static class
Ordering.IncomparableValueException

Exception thrown by a Ordering#explicit(List) or Ordering#explicit(Object, Object[]) comparator when comparing a value outside the set of values it can compare.

Field Summary

Modifier and TypeField and Description
pack-priv static final int
pack-priv static final int

Constructor Summary

AccessConstructor and Description
protected
Ordering()

Constructs a new instance of this class (only invokable by the subclass constructor, typically implicit).

Method Summary

Modifier and TypeMethod and Description
public static Ordering<@Nullable 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.

public static Ordering<@Nullable Object>
arbitrary()

Returns an arbitrary ordering over all objects, for which compare(a, b) == 0 implies a == b (identity equality).

public int
binarySearch(List<? extends T>
the list to be searched
sortedList
,
T
the key to be searched for
key
)

Searches sortedList for key using the binary search algorithm.
public abstract int
compare(T
the first object to be compared.
left
,
T
the second object to be compared.
right
)

Redeclares java.util.Comparator.compare.

Compares its two arguments for order.
public <U extends T> Ordering<U>
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.

public static <T extends @Nullable Object> Ordering<T>
compound(Iterable<? extends Comparator<? super T>>
the comparators to try in order
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.

public static <T> Ordering<T>

Returns:

the comparator described above
explicit
(List<T>
the values that the returned comparator will be able to compare, in the order the comparator should induce
valuesInOrder
)

Returns an ordering that compares objects according to the order in which they appear in the given list.

public static <T> Ordering<T>

Returns:

the comparator described above
explicit
(T
the value which the returned comparator should consider the "least" of all values
leastValue
,
T...
the rest of the values that the returned comparator will be able to compare, in the order the comparator should follow
remainingValuesInOrder
)

Returns an ordering that compares objects according to the order in which they are given to this method.

public static <T extends @Nullable Object> Ordering<T>

Returns:

comparator itself if it is already an Ordering; otherwise an ordering that wraps that comparator
from
(Comparator<T>
the comparator that defines the order
comparator
)

Returns an ordering based on an existing comparator instance.

public static <T extends @Nullable Object> Ordering<T>
from(Ordering<T> ordering)

Deprecated no need to use this
Simply returns its argument.
public <E extends T> List<E>

Returns:

an immutable RandomAccess list of the k greatest elements in descending order
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.

public <E extends T> List<E>

Returns:

an immutable RandomAccess list of the k greatest elements in descending order
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.

public <E extends @NonNull T> ImmutableList<E>
immutableSortedCopy(Iterable<E> elements)

Returns an immutable list containing elements sorted by this ordering.

public 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.

public 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.

public <E extends T> List<E>

Returns:

an immutable RandomAccess list of the k least elements in ascending order
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.

public <E extends T> List<E>

Returns:

an immutable RandomAccess list of the k least elements in ascending order
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.

public <S extends T> Ordering<Iterable<S>>
lexicographical()

Returns a new ordering which sorts iterables by comparing corresponding elements pairwise until a nonzero result is found; imposes "dictionary order".

public <E extends T> E
max(Iterator<E>
the iterator whose maximum element is to be determined
iterator
)

Returns the greatest of the specified values according to this ordering.

public <E extends T> E
max(Iterable<E>
the iterable whose maximum element is to be determined
iterable
)

Returns the greatest of the specified values according to this ordering.

public <E extends T> E
max(E
value to compare, returned if greater than or equal to b.
a
,
E
value to compare.
b
)

Returns the greater of the two values according to this ordering.

public <E extends T> E
max(E
value to compare, returned if greater than or equal to the rest.
a
,
E
value to compare
b
,
E
value to compare
c
,
E...
values to compare
rest
)

Returns the greatest of the specified values according to this ordering.

public <E extends T> E
min(Iterator<E>
the iterator whose minimum element is to be determined
iterator
)

Returns the least of the specified values according to this ordering.

public <E extends T> E
min(Iterable<E>
the iterable whose minimum element is to be determined
iterable
)

Returns the least of the specified values according to this ordering.

public <E extends T> E
min(E
value to compare, returned if less than or equal to b.
a
,
E
value to compare.
b
)

Returns the lesser of the two values according to this ordering.

public <E extends T> E
min(E
value to compare, returned if less than or equal to the rest.
a
,
E
value to compare
b
,
E
value to compare
c
,
E...
values to compare
rest
)

Returns the least of the specified values according to this ordering.

public static <C extends Comparable<T>> Ordering<C>
natural()

Returns a serializable ordering that uses the natural order of the values.

public <S extends T> Ordering<@Nullable S>
nullsFirst()

Returns an ordering that treats null as less than all other values and uses this to compare non-null values.

public <S extends T> Ordering<@Nullable S>
nullsLast()

Returns an ordering that treats null as greater than all other values and uses this ordering to compare non-null values.

pack-priv <T2 extends T> Ordering<Map.Entry<T2, ?>>
public <F extends @Nullable Object> 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.

public <S extends T> Ordering<S>
reverse()

Returns the reverse of this ordering; the Ordering equivalent to Collections#reverseOrder(Comparator).

public <E extends T> List<E>
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.

public static Ordering<Object>
usingToString()

Returns an ordering that compares objects by the natural ordering of their string representations as returned by toString().

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait