com.google.common.collect
Class Ordering<T>

java.lang.Object
  extended by com.google.common.collect.Ordering<T>
All Implemented Interfaces:
Comparator<T>

public abstract class Ordering<T>
extends Object
implements Comparator<T>

A comparator with added methods to support common functions. For example:

   if (Ordering.from(comparator).reverse().isOrdered(list)) { ... }

The from(Comparator) method returns the equivalent Ordering instance for a pre-existing comparator. You can also skip the comparator step and extend Ordering directly:

   Ordering<String> byLengthOrdering = new Ordering<String>() {
     public int compare(String left, String right) {
       return Ints.compare(left.length(), right.length());
     }
   };
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.

Since:
2010.01.04 stable (imported from Google Collections Library)
Author:
Jesse Wilson, Kevin Bourrillion

Constructor Summary
protected Ordering()
          Constructs a new instance of this class (only invokable by the subclass constructor, typically implicit).
 
Method Summary
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)
          Searches sortedList for key using the binary search algorithm.
<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.
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 for a pre-existing comparator.
static
<T> Ordering<T>
from(Ordering<T> ordering)
          Deprecated. no need to use this
 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.
<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".
<E extends T>
E
max(E a, E b)
          Returns the larger of the two values according to this ordering.
<E extends T>
E
max(E a, E b, E c, E... rest)
          Returns the largest of the specified values according to this ordering.
<E extends T>
E
max(Iterable<E> iterable)
          Returns the largest of the specified values according to this ordering.
<E extends T>
E
min(E a, E b)
          Returns the smaller of the two values according to this ordering.
<E extends T>
E
min(E a, E b, E c, E... rest)
          Returns the smallest of the specified values according to this ordering.
<E extends T>
E
min(Iterable<E> iterable)
          Returns the smallest 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.
<S extends T>
Ordering<S>
nullsFirst()
          Returns an ordering that treats null as less than all other values and uses this to compare non-null values.
<S extends T>
Ordering<S>
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>
Ordering<S>
reverse()
          Returns the reverse of this ordering; the Ordering equivalent to Collections.reverseOrder(Comparator).
<E extends T>
List<E>
sortedCopy(Iterable<E> iterable)
          Returns a copy of the given iterable sorted by this ordering.
static Ordering<Object> usingToString()
          Returns an ordering that compares objects by the natural ordering of their string representations as returned by toString().
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface java.util.Comparator
compare, equals
 

Constructor Detail

Ordering

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

Method Detail

natural

public static <C extends Comparable> Ordering<C> natural()
Returns a serializable ordering that uses the natural order of the values. The ordering throws a 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.


from

public static <T> Ordering<T> from(Comparator<T> comparator)
Returns an ordering for a pre-existing comparator. Note that if the comparator is not pre-existing, and you don't require serialization, you can subclass Ordering and implement its compare method instead.

Parameters:
comparator - the comparator that defines the order

from

@Deprecated
public static <T> Ordering<T> from(Ordering<T> ordering)
Deprecated. no need to use this

Simply returns its argument.


explicit

public 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. Only objects present in the list (according to 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 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:
NullPointerException - if any of the provided values is null
IllegalArgumentException - if valuesInOrder contains any duplicate values (according to Object.equals(java.lang.Object))

explicit

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

Parameters:
leastValue - the value which the returned comparator should consider the "least" of all values
remainingValuesInOrder - 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 null
IllegalArgumentException - if any duplicate values (according to Object.equals(Object)) are present among the method arguments

arbitrary

public static Ordering<Object> arbitrary()
Returns an arbitrary ordering over all objects, for which 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.

Since:
2010.01.04 tentative

usingToString

public static Ordering<Object> usingToString()
Returns an ordering that compares objects by the natural ordering of their string representations as returned by toString(). It does not support null values.

The comparator is serializable.


compound

public 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. The returned ordering is based on the state of the 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.

Parameters:
comparators - the comparators to try in order

compound

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


reverse

public <S extends T> Ordering<S> reverse()
Returns the reverse of this ordering; the Ordering equivalent to Collections.reverseOrder(Comparator).


onResultOf

public <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. For example, to compare objects by their string forms, in a case-insensitive manner, use:
   Ordering.from(String.CASE_INSENSITIVE_ORDER)
       .onResultOf(Functions.toStringFunction())


lexicographical

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". 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 to ordering.reverse().lexicographical() (consider how each would order [1] and [1, 1]).

Since:
2010.01.04 tentative

nullsFirst

public <S extends T> Ordering<S> nullsFirst()
Returns an ordering that treats null as less than all other values and uses this to compare non-null values.


nullsLast

public <S extends T> Ordering<S> nullsLast()
Returns an ordering that treats null as greater than all other values and uses this ordering to compare non-null values.


binarySearch

public int binarySearch(List<? extends T> sortedList,
                        T key)
Searches sortedList for key using the binary search algorithm. The list must be sorted using this ordering.

Parameters:
sortedList - the list to be searched
key - the key to be searched for

sortedCopy

public <E extends T> List<E> sortedCopy(Iterable<E> iterable)
Returns a copy of the given iterable sorted by this ordering. The input is not modified. The returned list is modifiable, serializable, and has random access.

Unlike Sets.newTreeSet(Iterable), this method does not collapse elements that compare as zero, and the resulting collection does not maintain its own sort order.

Parameters:
iterable - the elements to be copied and sorted
Returns:
a new list containing the given elements in sorted order

isOrdered

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. Note that this is always true when the iterable has fewer than two elements.


isStrictlyOrdered

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. Note that this is always true when the iterable has fewer than two elements.


max

public <E extends T> E max(Iterable<E> iterable)
Returns the largest of the specified values according to this ordering. If there are multiple largest values, the first of those is returned.

Parameters:
iterable - the iterable whose maximum element is to be determined
Throws:
NoSuchElementException - if iterable is empty
ClassCastException - if the parameters are not mutually comparable under this ordering.

max

public <E extends T> E max(E a,
                           E b,
                           E c,
                           E... rest)
Returns the largest of the specified values according to this ordering. If there are multiple largest values, the first of those is returned.

Parameters:
a - value to compare, returned if greater than or equal to the rest.
b - value to compare
c - value to compare
rest - values to compare
Throws:
ClassCastException - if the parameters are not mutually comparable under this ordering.

max

public <E extends T> E max(E a,
                           E b)
Returns the larger 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:
ClassCastException - if the parameters are not mutually comparable under this ordering.

min

public <E extends T> E min(Iterable<E> iterable)
Returns the smallest of the specified values according to this ordering. If there are multiple smallest values, the first of those is returned.

Parameters:
iterable - the iterable whose minimum element is to be determined
Throws:
NoSuchElementException - if iterable is empty
ClassCastException - if the parameters are not mutually comparable under this ordering.

min

public <E extends T> E min(E a,
                           E b,
                           E c,
                           E... rest)
Returns the smallest of the specified values according to this ordering. If there are multiple smallest values, the first of those is returned.

Parameters:
a - value to compare, returned if less than or equal to the rest.
b - value to compare
c - value to compare
rest - values to compare
Throws:
ClassCastException - if the parameters are not mutually comparable under this ordering.

min

public <E extends T> E min(E a,
                           E b)
Returns the smaller 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:
ClassCastException - if the parameters are not mutually comparable under this ordering.