Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2007 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.collect;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.collect.CollectPreconditions.checkNonnegative;
 
 
 import java.util.List;
 import java.util.Map;
 
A comparator, with additional methods to support common operations. This is an "enriched" version of Comparator, in the same sense that FluentIterable is an enriched java.lang.Iterable.

The common ways to get an instance of Ordering are:

Then you can use the chaining methods to get an altered version of that Ordering, including:

Finally, use the resulting Ordering anywhere a java.util.Comparator is required, or use any of its special operations, such as:

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.

See the Guava User Guide article on Ordering.

Author(s):
Jesse Wilson
Kevin Bourrillion
Since:
2.0 (imported from Google Collections Library)
 
 public abstract class Ordering<T> implements Comparator<T> {
   // Natural order
 
  
Returns a serializable ordering that uses the natural order of the values. The ordering throws a java.lang.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.

  @GwtCompatible(serializable = true)
  @SuppressWarnings("unchecked"// TODO(kevinb): right way to explain this??
  public static <C extends ComparableOrdering<C> natural() {
    return (Ordering<C>) .;
  }
  // Static factories

  
Returns an ordering based on an existing comparator instance. Note that it is unnecessary to create a new anonymous inner class implementing Comparator just to pass it in here. Instead, simply subclass Ordering and implement its compare 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
  @GwtCompatible(serializable = true)
  public static <T> Ordering<T> from(Comparator<T> comparator) {
    return (comparator instanceof Ordering)
        ? (Ordering<T>) comparator
        : new ComparatorOrdering<T>(comparator);
  }

  
Simply returns its argument.

Deprecated:
no need to use this
  @GwtCompatible(serializable = true)
  @Deprecated public static <T> Ordering<T> from(Ordering<T> ordering) {
    return checkNotNull(ordering);
  }

  
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 java.lang.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 java.lang.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 null
java.lang.IllegalArgumentException if valuesInOrder contains any duplicate values (according to java.lang.Object.equals(java.lang.Object))
  @GwtCompatible(serializable = true)
  public static <T> Ordering<T> explicit(List<T> valuesInOrder) {
    return new ExplicitOrdering<T>(valuesInOrder);
  }

  
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 java.lang.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 java.lang.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:
java.lang.NullPointerException if any of the provided values is null
java.lang.IllegalArgumentException if any duplicate values (according to java.lang.Object.equals(java.lang.Object)) are present among the method arguments
  @GwtCompatible(serializable = true)
  public static <T> Ordering<T> explicit(
      T leastValue, T... remainingValuesInOrder) {
    return explicit(Lists.asList(leastValueremainingValuesInOrder));
  }
  // Ordering<Object> singletons

  
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 that sortedCopy(java.lang.Iterable) and immutableSortedCopy(java.lang.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, e and s 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 implement java.lang.Comparable at all).

Warning: by definition, this comparator is not consistent with equals (as defined here). Avoid its use in APIs, such as java.util.TreeSet.(java.util.Comparator), where such consistency is expected.

The returned comparator is serializable.

Since:
13.0
  @GwtCompatible(serializable = true)
  @SuppressWarnings("unchecked")
  public static Ordering<ObjectallEqual() {
    return .;
  }

  
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.

  @GwtCompatible(serializable = true)
  public static Ordering<ObjectusingToString() {
  }

  
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 java.lang.Object.equals(java.lang.Object)" as defined by java.util.Comparator. Use caution when building a java.util.SortedSet or java.util.SortedMap from it, as the resulting collection will not behave exactly according to spec.

This ordering is not serializable, as its implementation relies on java.lang.System.identityHashCode(java.lang.Object), so its behavior cannot be preserved across serialization.

Since:
2.0
  public static Ordering<Objectarbitrary() {
  }
  private static class ArbitraryOrderingHolder {
    static final Ordering<ObjectARBITRARY_ORDERING = new ArbitraryOrdering();
  }
  @VisibleForTesting static class ArbitraryOrdering extends Ordering<Object> {
    @SuppressWarnings("deprecation"// TODO(kevinb): ?
    private Map<ObjectIntegeruids =
        Platform.tryWeakKeys(new MapMaker()).makeComputingMap(
            new Function<ObjectInteger>() {
              final AtomicInteger counter = new AtomicInteger(0);
              @Override
              public Integer apply(Object from) {
                return .getAndIncrement();
              }
            });
    @Override public int compare(Object leftObject right) {
      if (left == right) {
        return 0;
      } else if (left == null) {
        return -1;
      } else if (right == null) {
        return 1;
      }
      int leftCode = identityHashCode(left);
      int rightCode = identityHashCode(right);
      if (leftCode != rightCode) {
        return leftCode < rightCode ? -1 : 1;
      }
      // identityHashCode collision (rare, but not as rare as you'd think)
      int result = .get(left).compareTo(.get(right));
      if (result == 0) {
        throw new AssertionError(); // extremely, extremely unlikely.
      }
      return result;
    }
    @Override public String toString() {
      return "Ordering.arbitrary()";
    }
    /*
     * We need to be able to mock identityHashCode() calls for tests, because it
     * can take 1-10 seconds to find colliding objects. Mocking frameworks that
     * can do magic to mock static method calls still can't do so for a system
     * class, so we need the indirection. In production, Hotspot should still
     * recognize that the call is 1-morphic and should still be willing to
     * inline it if necessary.
     */
    int identityHashCode(Object object) {
      return System.identityHashCode(object);
    }
  }
  // Constructor

  
Constructs a new instance of this class (only invokable by the subclass constructor, typically implicit).
  protected Ordering() {}
  // Instance-based factories (and any static equivalents)

  
Returns the reverse of this ordering; the Ordering equivalent to java.util.Collections.reverseOrder(java.util.Comparator).
  // type parameter <S> lets us avoid the extra <String> in statements like:
  // Ordering<String> o = Ordering.<String>natural().reverse();
  @GwtCompatible(serializable = true)
  public <S extends T> Ordering<S> reverse() {
    return new ReverseOrdering<S>(this);
  }

  
Returns an ordering that treats null as less than all other values and uses this to compare non-null values.
  // type parameter <S> lets us avoid the extra <String> in statements like:
  // Ordering<String> o = Ordering.<String>natural().nullsFirst();
  @GwtCompatible(serializable = true)
  public <S extends T> Ordering<S> nullsFirst() {
    return new NullsFirstOrdering<S>(this);
  }

  
Returns an ordering that treats null as greater than all other values and uses this ordering to compare non-null values.
  // type parameter <S> lets us avoid the extra <String> in statements like:
  // Ordering<String> o = Ordering.<String>natural().nullsLast();
  @GwtCompatible(serializable = true)
  public <S extends T> Ordering<S> nullsLast() {
    return new NullsLastOrdering<S>(this);
  }

  
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())
  @GwtCompatible(serializable = true)
  public <F> Ordering<F> onResultOf(Function<F, ? extends T> function) {
    return new ByFunctionOrdering<F, T>(functionthis);
  }
  <T2 extends T> Ordering<Map.Entry<T2, ?>> onKeys() {
    return onResultOf(Maps.<T2>keyFunction());
  }

  
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(java.lang.Iterable) on the same component comparators.

  @GwtCompatible(serializable = true)
  public <U extends T> Ordering<U> compound(
      Comparator<? super U> secondaryComparator) {
    return new CompoundOrdering<U>(thischeckNotNull(secondaryComparator));
  }

  
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 java.util.HashSet, will produce non-deterministic results.

Parameters:
comparators the comparators to try in order
  @GwtCompatible(serializable = true)
  public static <T> Ordering<T> compound(
      Iterable<? extends Comparator<? super T>> comparators) {
    return new CompoundOrdering<T>(comparators);
  }

  
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:
2.0
  @GwtCompatible(serializable = true)
  // type parameter <S> lets us avoid the extra <String> in statements like:
  // Ordering<Iterable<String>> o =
  //     Ordering.<String>natural().lexicographical();
  public <S extends T> Ordering<Iterable<S>> lexicographical() {
    /*
     * Note that technically the returned ordering should be capable of
     * handling not just {@code Iterable<S>} instances, but also any {@code
     * Iterable<? extends S>}. However, the need for this comes up so rarely
     * that it doesn't justify making everyone else deal with the very ugly
     * wildcard.
     */
    return new LexicographicalOrdering<S>(this);
  }
  // Regular instance methods
  // Override to add @Nullable
  @Override public abstract int compare(@Nullable T left, @Nullable T right);

  
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: its hasNext() method will return false.

Parameters:
iterator the iterator whose minimum element is to be determined
Throws:
java.util.NoSuchElementException if iterator is empty
java.lang.ClassCastException if the parameters are not mutually comparable under this ordering.
Since:
11.0
  public <E extends T> E min(Iterator<E> iterator) {
    // let this throw NoSuchElementException as necessary
    E minSoFar = iterator.next();
    while (iterator.hasNext()) {
      minSoFar = min(minSoFariterator.next());
    }
    return minSoFar;
  }

  
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 if iterable is empty
java.lang.ClassCastException if the parameters are not mutually comparable under this ordering.
  public <E extends T> E min(Iterable<E> iterable) {
    return min(iterable.iterator());
  }

  
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.
  public <E extends T> E min(@Nullable E a, @Nullable E b) {
    return (compare(ab) <= 0) ? a : b;
  }

  
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 compare
c value to compare
rest values to compare
Throws:
java.lang.ClassCastException if the parameters are not mutually comparable under this ordering.
  public <E extends T> E min(
      @Nullable E a, @Nullable E b, @Nullable E c, E... rest) {
    E minSoFar = min(min(ab), c);
    for (E r : rest) {
      minSoFar = min(minSoFarr);
    }
    return minSoFar;
  }

  
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: its hasNext() method will return false.

Parameters:
iterator the iterator whose maximum element is to be determined
Throws:
java.util.NoSuchElementException if iterator is empty
java.lang.ClassCastException if the parameters are not mutually comparable under this ordering.
Since:
11.0
  public <E extends T> E max(Iterator<E> iterator) {
    // let this throw NoSuchElementException as necessary
    E maxSoFar = iterator.next();
    while (iterator.hasNext()) {
      maxSoFar = max(maxSoFariterator.next());
    }
    return maxSoFar;
  }

  
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 if iterable is empty
java.lang.ClassCastException if the parameters are not mutually comparable under this ordering.
  public <E extends T> E max(Iterable<E> iterable) {
    return max(iterable.iterator());
  }

  
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.
  public <E extends T> E max(@Nullable E a, @Nullable E b) {
    return (compare(ab) >= 0) ? a : b;
  }

  
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 compare
c value to compare
rest values to compare
Throws:
java.lang.ClassCastException if the parameters are not mutually comparable under this ordering.
  public <E extends T> E max(
      @Nullable E a, @Nullable E b, @Nullable E c, E... rest) {
    E maxSoFar = max(max(ab), c);
    for (E r : rest) {
      maxSoFar = max(maxSoFarr);
    }
    return maxSoFar;
  }

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

Returns:
an immutable RandomAccess list of the k least elements in ascending order
Throws:
java.lang.IllegalArgumentException if k is negative
Since:
8.0
  public <E extends T> List<E> leastOf(Iterable<E> iterableint k) {
    if (iterable instanceof Collection) {
      Collection<E> collection = (Collection<E>) iterable;
      if (collection.size() <= 2L * k) {
        // In this case, just dumping the collection to an array and sorting is
        // faster than using the implementation for Iterator, which is
        // specialized for k much smaller than n.
        @SuppressWarnings("unchecked"// c only contains E's and doesn't escape
        E[] array = (E[]) collection.toArray();
        Arrays.sort(arraythis);
        if (array.length > k) {
          array = ObjectArrays.arraysCopyOf(arrayk);
        }
        return Collections.unmodifiableList(Arrays.asList(array));
      }
    }
    return leastOf(iterable.iterator(), k);
  }

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

Returns:
an immutable RandomAccess list of the k least elements in ascending order
Throws:
java.lang.IllegalArgumentException if k is negative
Since:
14.0
  public <E extends T> List<E> leastOf(Iterator<E> elementsint k) {
    checkNotNull(elements);
    checkNonnegative(k"k");
    if (k == 0 || !elements.hasNext()) {
      return ImmutableList.of();
    } else if (k >= . / 2) {
      // k is really large; just do a straightforward sorted-copy-and-sublist
      ArrayList<E> list = Lists.newArrayList(elements);
      Collections.sort(listthis);
      if (list.size() > k) {
        list.subList(klist.size()).clear();
      }
      list.trimToSize();
      return Collections.unmodifiableList(list);
    }
    /*
     * Our goal is an O(n) algorithm using only one pass and O(k) additional
     * memory.
     *
     * We use the following algorithm: maintain a buffer of size 2*k. Every time
     * the buffer gets full, find the median and partition around it, keeping
     * only the lowest k elements.  This requires n/k find-median-and-partition
     * steps, each of which take O(k) time with a traditional quickselect.
     *
     * After sorting the output, the whole algorithm is O(n + k log k). It
     * degrades gracefully for worst-case input (descending order), performs
     * competitively or wins outright for randomly ordered input, and doesn't
     * require the whole collection to fit into memory.
     */
    int bufferCap = k * 2;
    @SuppressWarnings("unchecked"// we'll only put E's in
    E[] buffer = (E[]) new Object[bufferCap];
    E threshold = elements.next();
    buffer[0] = threshold;
    int bufferSize = 1;
    // threshold is the kth smallest element seen so far.  Once bufferSize >= k,
    // anything larger than threshold can be ignored immediately.
    while (bufferSize < k && elements.hasNext()) {
      E e = elements.next();
      buffer[bufferSize++] = e;
      threshold = max(thresholde);
    }
    while (elements.hasNext()) {
      E e = elements.next();
      if (compare(ethreshold) >= 0) {
        continue;
      }
      buffer[bufferSize++] = e;
      if (bufferSize == bufferCap) {
        // We apply the quickselect algorithm to partition about the median,
        // and then ignore the last k elements.
        int left = 0;
        int right = bufferCap - 1;
        int minThresholdPosition = 0;
        // The leftmost position at which the greatest of the k lower elements
        // -- the new value of threshold -- might be found.
        while (left < right) {
          int pivotIndex = (left + right + 1) >>> 1;
          int pivotNewIndex = partition(bufferleftrightpivotIndex);
          if (pivotNewIndex > k) {
            right = pivotNewIndex - 1;
          } else if (pivotNewIndex < k) {
            left = Math.max(pivotNewIndexleft + 1);
            minThresholdPosition = pivotNewIndex;
          } else {
            break;
          }
        }
        bufferSize = k;
        threshold = buffer[minThresholdPosition];
        for (int i = minThresholdPosition + 1; i < bufferSizei++) {
          threshold = max(thresholdbuffer[i]);
        }
      }
    }
    Arrays.sort(buffer, 0, bufferSizethis);
    bufferSize = Math.min(bufferSizek);
    return Collections.unmodifiableList(
        Arrays.asList(ObjectArrays.arraysCopyOf(bufferbufferSize)));
    // We can't use ImmutableList; we have to be null-friendly!
  }
  private <E extends T> int partition(
      E[] valuesint leftint rightint pivotIndex) {
    E pivotValue = values[pivotIndex];
    values[pivotIndex] = values[right];
    values[right] = pivotValue;
    int storeIndex = left;
    for (int i = lefti < righti++) {
      if (compare(values[i], pivotValue) < 0) {
        ObjectArrays.swap(valuesstoreIndexi);
        storeIndex++;
      }
    }
    ObjectArrays.swap(valuesrightstoreIndex);
    return storeIndex;
  }

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

Returns:
an immutable RandomAccess list of the k greatest elements in descending order
Throws:
java.lang.IllegalArgumentException if k is negative
Since:
8.0
  public <E extends T> List<E> greatestOf(Iterable<E> iterableint k) {
    // TODO(kevinb): see if delegation is hurting performance noticeably
    // TODO(kevinb): if we change this implementation, add full unit tests.
    return reverse().leastOf(iterablek);
  }

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

Returns:
an immutable RandomAccess list of the k greatest elements in descending order
Throws:
java.lang.IllegalArgumentException if k is negative
Since:
14.0
  public <E extends T> List<E> greatestOf(Iterator<E> iteratorint k) {
    return reverse().leastOf(iteratork);
  }

  
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. The input is not modified. The returned list is serializable and has random access.

Unlike Sets.newTreeSet(java.lang.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) 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 java.util.Collections.sort(java.util.List).

  public <E extends T> List<E> sortedCopy(Iterable<E> elements) {
    @SuppressWarnings("unchecked"// does not escape, and contains only E's
    E[] array = (E[]) Iterables.toArray(elements);
    Arrays.sort(arraythis);
    return Lists.newArrayList(Arrays.asList(array));
  }

  
Returns an immutable list containing elements sorted by this ordering. The input is not modified.

Unlike Sets.newTreeSet(java.lang.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.

Throws:
java.lang.NullPointerException if any of elements (or elements itself) is null
Since:
3.0
  public <E extends T> ImmutableList<E> immutableSortedCopy(
      Iterable<E> elements) {
    @SuppressWarnings("unchecked"// we'll only ever have E's in here
    E[] array = (E[]) Iterables.toArray(elements);
    for (E e : array) {
      checkNotNull(e);
    }
    Arrays.sort(arraythis);
    return ImmutableList.asImmutableList(array);
  }

  
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.
  public boolean isOrdered(Iterable<? extends T> iterable) {
    Iterator<? extends T> it = iterable.iterator();
    if (it.hasNext()) {
      T prev = it.next();
      while (it.hasNext()) {
        T next = it.next();
        if (compare(prevnext) > 0) {
          return false;
        }
        prev = next;
      }
    }
    return true;
  }

  
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.
  public boolean isStrictlyOrdered(Iterable<? extends T> iterable) {
    Iterator<? extends T> it = iterable.iterator();
    if (it.hasNext()) {
      T prev = it.next();
      while (it.hasNext()) {
        T next = it.next();
        if (compare(prevnext) >= 0) {
          return false;
        }
        prev = next;
      }
    }
    return true;
  }

  
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
  public int binarySearch(List<? extends T> sortedList, @Nullable T key) {
    return Collections.binarySearch(sortedListkeythis);
  }

  
Exception thrown by a Ordering.explicit(java.util.List) or Ordering.explicit(java.lang.Object,java.lang.Object[]) comparator when comparing a value outside the set of values it can compare. Extending java.lang.ClassCastException may seem odd, but it is required.
  // TODO(kevinb): make this public, document it right
  static class IncomparableValueException extends ClassCastException {
    final Object value;
      super("Cannot compare value: " + value);
      this. = value;
    }
    private static final long serialVersionUID = 0;
  }
  // Never make these public
  static final int LEFT_IS_GREATER = 1;
  static final int RIGHT_IS_GREATER = -1;
New to GrepCode? Check out our FAQ X