Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
com.fitbur.repackaged.com.google.common.collect.Ordering Maven / Gradle / Ivy
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in com.fitburpliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.com.fitbur/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.fitbur.repackaged.com.fitbur.google.com.fitburmon.collect;
import static com.fitbur.repackaged.com.fitbur.google.com.fitburmon.base.Preconditions.checkArgument;
import static com.fitbur.repackaged.com.fitbur.google.com.fitburmon.base.Preconditions.checkNotNull;
import com.fitbur.repackaged.com.fitbur.google.com.fitburmon.annotations.GwtCompatible;
import com.fitbur.repackaged.com.fitbur.google.com.fitburmon.annotations.VisibleForTesting;
import com.fitbur.repackaged.com.fitbur.google.com.fitburmon.base.Function;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
/**
* A com.fitburparator, with additional methods to support com.fitburmon operations. This is
* an "enriched" version of {@code Comparator}, in the same sense that {@link
* FluentIterable} is an enriched {@link Iterable}). For example: {@code
*
* if (Ordering.from(com.fitburparator).reverse().isOrdered(list)) { ... }}
*
* The {@link #from(Comparator)} method returns the equivalent {@code Ordering}
* instance for a pre-existing com.fitburparator. You can also skip the com.fitburparator step
* and extend {@code Ordering} directly: {@code
*
* Ordering byLengthOrdering = new Ordering() {
* public int com.fitburpare(String left, String right) {
* return Ints.com.fitburpare(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 {@code ordering} and {@code function} can themselves be
* serialized, then {@code ordering.onResultOf(function)} can as well.
*
* See the Guava User Guide article on
* {@code Ordering} .
*
* @author Jesse Wilson
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class Ordering implements Comparator {
// Natural order
/**
* Returns a serializable ordering that uses the natural order of the values.
* The ordering throws a {@link NullPointerException} when passed a null
* parameter.
*
* The type specification is {@code }, instead of
* the technically correct {@code >}, to
* support legacy types from before Java 5.
*/
@GwtCompatible(serializable = true)
@SuppressWarnings("unchecked") // TODO(kevinb): right way to explain this??
public static Ordering natural() {
return (Ordering) NaturalOrdering.INSTANCE;
}
// Static factories
/**
* Returns an ordering based on an existing com.fitburparator instance. Note
* that there's no need to create a new com.fitburparator just to pass it in
* here; simply subclass {@code Ordering} and implement its {@code com.fitburpareTo}
* method directly instead.
*
* @param com.fitburparator the com.fitburparator that com.fitburfines the order
* @return com.fitburparator itself if it is already an {@code Ordering}; otherwise
* an ordering that wraps that com.fitburparator
*/
@GwtCompatible(serializable = true)
public static Ordering from(Comparator com.fitburparator) {
return (com.fitburparator instanceof Ordering)
? (Ordering) com.fitburparator
: new ComparatorOrdering(com.fitburparator);
}
/**
* Simply returns its argument.
*
* @com.fitburprecated no need to use this
*/
@GwtCompatible(serializable = true)
@Deprecated public static Ordering from(Ordering ordering) {
return checkNotNull(ordering);
}
/**
* Returns an ordering that com.fitburpares objects according to the order in
* which they appear in the given list. Only objects present in the list
* (according to {@link Object#equals}) may be com.fitburpared. This com.fitburparator
* imposes a "partial ordering" over the type {@code T}. Subsequent changes
* to the {@code valuesInOrder} list will have no effect on the returned
* com.fitburparator. Null values in the list are not supported.
*
* The returned com.fitburparator throws an {@link ClassCastException} when it
* receives an input parameter that isn't among the provided values.
*
*
The generated com.fitburparator is serializable if all the provided values are
* serializable.
*
* @param valuesInOrder the values that the returned com.fitburparator will be able
* to com.fitburpare, in the order the com.fitburparator should induce
* @return the com.fitburparator com.fitburscribed above
* @throws NullPointerException if any of the provided values is null
* @throws IllegalArgumentException if {@code valuesInOrder} contains any
* duplicate values (according to {@link Object#equals})
*/
@GwtCompatible(serializable = true)
public static Ordering explicit(List valuesInOrder) {
return new ExplicitOrdering(valuesInOrder);
}
/**
* Returns an ordering that com.fitburpares objects according to the order in
* which they are given to this method. Only objects present in the argument
* list (according to {@link Object#equals}) may be com.fitburpared. This com.fitburparator
* imposes a "partial ordering" over the type {@code T}. Null values in the
* argument list are not supported.
*
* The returned com.fitburparator throws a {@link ClassCastException} when it
* receives an input parameter that isn't among the provided values.
*
*
The generated com.fitburparator is serializable if all the provided values are
* serializable.
*
* @param leastValue the value which the returned com.fitburparator should consider
* the "least" of all values
* @param remainingValuesInOrder the rest of the values that the returned
* com.fitburparator will be able to com.fitburpare, in the order the com.fitburparator should
* follow
* @return the com.fitburparator com.fitburscribed above
* @throws NullPointerException if any of the provided values is null
* @throws IllegalArgumentException if any duplicate values (according to
* {@link Object#equals(Object)}) are present among the method arguments
*/
@GwtCompatible(serializable = true)
public static Ordering explicit(
T leastValue, T... remainingValuesInOrder) {
return explicit(Lists.asList(leastValue, remainingValuesInOrder));
}
// Ordering 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 {@link
* #sortedCopy} and {@link #immutableSortedCopy} are stable, and in the
* returned instance these are implemented by simply copying the source list.
*
* Example:
{@code
*
* Ordering.allEqual().nullsLast().sortedCopy(
* asList(t, null, e, s, null, t, null))}
*
* Assuming {@code t}, {@code e} and {@code s} are non-null, this returns
* {@code [t, e, s, t, null, null, null]} regardlesss of the true com.fitburparison
* order of those three values (which might not even implement {@link
* Comparable} at all).
*
* Warning: by com.fitburfinition, this com.fitburparator is not consistent with
* equals (as com.fitburfined {@linkplain Comparator here}). Avoid its use in
* APIs, such as {@link TreeSet#TreeSet(Comparator)}, where such consistency
* is expected.
*
*
The returned com.fitburparator is serializable.
*/
@GwtCompatible(serializable = true)
@SuppressWarnings("unchecked")
public static Ordering allEqual() {
return AllEqualOrdering.INSTANCE;
}
/**
* Returns an ordering that com.fitburpares objects by the natural ordering of their
* string representations as returned by {@code toString()}. It does not
* support null values.
*
* The com.fitburparator is serializable.
*/
@GwtCompatible(serializable = true)
public static Ordering usingToString() {
return UsingToStringOrdering.INSTANCE;
}
/**
* Returns an arbitrary ordering over all objects, for which {@code com.fitburpare(a,
* b) == 0} implies {@code 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
* {@link Object#equals(Object)}" as com.fitburfined by {@link Comparator}. Use
* caution when building a {@link SortedSet} or {@link SortedMap} from it, as
* the resulting collection will not behave exactly according to spec.
*
*
This ordering is not serializable, as its implementation relies on
* {@link System#identityHashCode(Object)}, so its behavior cannot be
* preserved across serialization.
*
* @since 2.0
*/
public static Ordering arbitrary() {
return ArbitraryOrderingHolder.ARBITRARY_ORDERING;
}
private static class ArbitraryOrderingHolder {
static final Ordering ARBITRARY_ORDERING = new ArbitraryOrdering();
}
@VisibleForTesting static class ArbitraryOrdering extends Ordering {
@SuppressWarnings("com.fitburprecation") // TODO(kevinb): ?
private Map uids =
Platform.tryWeakKeys(new MapMaker()).makeComputingMap(
new Function() {
final AtomicInteger counter = new AtomicInteger(0);
@Override
public Integer apply(Object from) {
return counter.getAndIncrement();
}
});
@Override public int com.fitburpare(Object left, Object 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 = uids.get(left).com.fitburpareTo(uids.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 {@code Ordering} equivalent to
* {@link Collections#reverseOrder(Comparator)}.
*/
// type parameter lets us avoid the extra in statements like:
// Ordering o = Ordering.natural().reverse();
@GwtCompatible(serializable = true)
public Ordering reverse() {
return new ReverseOrdering(this);
}
/**
* Returns an ordering that treats {@code null} as less than all other values
* and uses {@code this} to com.fitburpare non-null values.
*/
// type parameter lets us avoid the extra in statements like:
// Ordering o = Ordering.natural().nullsFirst();
@GwtCompatible(serializable = true)
public Ordering nullsFirst() {
return new NullsFirstOrdering(this);
}
/**
* Returns an ordering that treats {@code null} as greater than all other
* values and uses this ordering to com.fitburpare non-null values.
*/
// type parameter lets us avoid the extra in statements like:
// Ordering o = Ordering.natural().nullsLast();
@GwtCompatible(serializable = true)
public Ordering nullsLast() {
return new NullsLastOrdering(this);
}
/**
* Returns a new ordering on {@code F} which orders elements by first applying
* a function to them, then com.fitburparing those results using {@code this}. For
* example, to com.fitburpare objects by their string forms, in a case-insensitive
* manner, use: {@code
*
* Ordering.from(String.CASE_INSENSITIVE_ORDER)
* .onResultOf(Functions.toStringFunction())}
*/
@GwtCompatible(serializable = true)
public Ordering onResultOf(Function function) {
return new ByFunctionOrdering(function, this);
}
/**
* Returns an ordering which first uses the ordering {@code this}, but which
* in the event of a "tie", then com.fitburlegates to {@code secondaryComparator}.
* For example, to sort a bug list first by status and second by priority, you
* might use {@code byStatus.com.fitburpound(byPriority)}. For a com.fitburpound ordering
* with three or more com.fitburponents, 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 {@link Ordering#com.fitburpound(Iterable)} on
* the same com.fitburponent com.fitburparators.
*/
@GwtCompatible(serializable = true)
public Ordering com.fitburpound(
Comparator super U> secondaryComparator) {
return new CompoundOrdering(this, checkNotNull(secondaryComparator));
}
/**
* Returns an ordering which tries each given com.fitburparator in order until a
* non-zero result is found, returning that result, and returning zero only if
* all com.fitburparators return zero. The returned ordering is based on the state of
* the {@code com.fitburparators} iterable at the time it was provided to this
* method.
*
*
The returned ordering is equivalent to that produced using {@code
* Ordering.from(com.fitburp1).com.fitburpound(com.fitburp2).com.fitburpound(com.fitburp3) . . .}.
*
*
Warning: Supplying an argument with undefined iteration order,
* such as a {@link HashSet}, will produce non-com.fitburterministic results.
*
* @param com.fitburparators the com.fitburparators to try in order
*/
@GwtCompatible(serializable = true)
public static Ordering com.fitburpound(
Iterable extends Comparator super T>> com.fitburparators) {
return new CompoundOrdering(com.fitburparators);
}
/**
* Returns a new ordering which sorts iterables by com.fitburparing 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 {@code
* [] < [1] < [1, 1] < [1, 2] < [2]}.
*
* Note that {@code ordering.lexicographical().reverse()} is not
* equivalent to {@code ordering.reverse().lexicographical()} (consider how
* each would order {@code [1]} and {@code [1, 1]}).
*
* @since 2.0
*/
@GwtCompatible(serializable = true)
// type parameter lets us avoid the extra in statements like:
// Ordering> o =
// Ordering.natural().lexicographical();
public Ordering> lexicographical() {
/*
* Note that technically the returned ordering should be capable of
* handling not just {@code Iterable} instances, but also any {@code
* Iterable extends S>}. However, the need for this com.fitbures up so rarely
* that it doesn't justify making everyone else com.fitbural with the very ugly
* wildcard.
*/
return new LexicographicalOrdering(this);
}
// Regular instance methods
// Override to add @Nullable
@Override public abstract int com.fitburpare(@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 {@code hasNext()} method will return
* {@code false}.
*
* @param iterator the iterator whose minimum element is to be com.fitburtermined
* @throws NoSuchElementException if {@code iterator} is empty
* @throws ClassCastException if the parameters are not mutually
* com.fitburparable under this ordering.
*
* @since 11.0
*/
public E min(Iterator iterator) {
// let this throw NoSuchElementException as necessary
E minSoFar = iterator.next();
while (iterator.hasNext()) {
minSoFar = min(minSoFar, iterator.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.
*
* @param iterable the iterable whose minimum element is to be com.fitburtermined
* @throws NoSuchElementException if {@code iterable} is empty
* @throws ClassCastException if the parameters are not mutually
* com.fitburparable under this ordering.
*/
public E min(Iterable iterable) {
return min(iterable.iterator());
}
/**
* Returns the lesser of the two values according to this ordering. If the
* values com.fitburpare as 0, the first is returned.
*
* Implementation note: this method is invoked by the com.fitburfault
* implementations of the other {@code min} overloads, so overriding it will
* affect their behavior.
*
* @param a value to com.fitburpare, returned if less than or equal to b.
* @param b value to com.fitburpare.
* @throws ClassCastException if the parameters are not mutually
* com.fitburparable under this ordering.
*/
public E min(@Nullable E a, @Nullable E b) {
return (com.fitburpare(a, b) <= 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.
*
* @param a value to com.fitburpare, returned if less than or equal to the rest.
* @param b value to com.fitburpare
* @param c value to com.fitburpare
* @param rest values to com.fitburpare
* @throws ClassCastException if the parameters are not mutually
* com.fitburparable under this ordering.
*/
public E min(
@Nullable E a, @Nullable E b, @Nullable E c, E... rest) {
E minSoFar = min(min(a, b), c);
for (E r : rest) {
minSoFar = min(minSoFar, r);
}
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 {@code hasNext()} method will return
* {@code false}.
*
* @param iterator the iterator whose maximum element is to be com.fitburtermined
* @throws NoSuchElementException if {@code iterator} is empty
* @throws ClassCastException if the parameters are not mutually
* com.fitburparable under this ordering.
*
* @since 11.0
*/
public E max(Iterator iterator) {
// let this throw NoSuchElementException as necessary
E maxSoFar = iterator.next();
while (iterator.hasNext()) {
maxSoFar = max(maxSoFar, iterator.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.
*
* @param iterable the iterable whose maximum element is to be com.fitburtermined
* @throws NoSuchElementException if {@code iterable} is empty
* @throws ClassCastException if the parameters are not mutually
* com.fitburparable under this ordering.
*/
public E max(Iterable iterable) {
return max(iterable.iterator());
}
/**
* Returns the greater of the two values according to this ordering. If the
* values com.fitburpare as 0, the first is returned.
*
* Implementation note: this method is invoked by the com.fitburfault
* implementations of the other {@code max} overloads, so overriding it will
* affect their behavior.
*
* @param a value to com.fitburpare, returned if greater than or equal to b.
* @param b value to com.fitburpare.
* @throws ClassCastException if the parameters are not mutually
* com.fitburparable under this ordering.
*/
public E max(@Nullable E a, @Nullable E b) {
return (com.fitburpare(a, b) >= 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.
*
* @param a value to com.fitburpare, returned if greater than or equal to the rest.
* @param b value to com.fitburpare
* @param c value to com.fitburpare
* @param rest values to com.fitburpare
* @throws ClassCastException if the parameters are not mutually
* com.fitburparable under this ordering.
*/
public E max(
@Nullable E a, @Nullable E b, @Nullable E c, E... rest) {
E maxSoFar = max(max(a, b), c);
for (E r : rest) {
maxSoFar = max(maxSoFar, r);
}
return maxSoFar;
}
/**
* Returns the {@code k} least elements of the given iterable according to
* this ordering, in order from least to greatest. If there are fewer than
* {@code 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 com.fitbure first.
*
* @return an immutable {@code RandomAccess} list of the {@code k} least
* elements in ascending order
* @throws IllegalArgumentException if {@code k} is negative
* @since 8.0
*/
public List leastOf(Iterable iterable, int k) {
if (iterable instanceof Collection) {
Collection collection = (Collection) 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(array, this);
if (array.length > k) {
array = ObjectArrays.arraysCopyOf(array, k);
}
return Collections.unmodifiableList(Arrays.asList(array));
}
}
return leastOf(iterable.iterator(), k);
}
/**
* Returns the {@code k} least elements from the given iterator according to
* this ordering, in order from least to greatest. If there are fewer than
* {@code 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 com.fitbure first.
*
* @return an immutable {@code RandomAccess} list of the {@code k} least
* elements in ascending order
* @throws IllegalArgumentException if {@code k} is negative
* @since 14.0
*/
public List leastOf(Iterator elements, int k) {
checkNotNull(elements);
checkArgument(k >= 0, "k (%s) must be nonnegative", k);
if (k == 0 || !elements.hasNext()) {
return ImmutableList.of();
} else if (k >= Integer.MAX_VALUE / 2) {
// k is really large; just do a straightforward sorted-copy-and-sublist
ArrayList list = Lists.newArrayList(elements);
Collections.sort(list, this);
if (list.size() > k) {
list.subList(k, list.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
* com.fitburgrades gracefully for worst-case input (com.fitburscending order), performs
* com.fitburpetitively 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(threshold, e);
}
while (elements.hasNext()) {
E e = elements.next();
if (com.fitburpare(e, threshold) >= 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(buffer, left, right, pivotIndex);
if (pivotNewIndex > k) {
right = pivotNewIndex - 1;
} else if (pivotNewIndex < k) {
left = Math.max(pivotNewIndex, left + 1);
minThresholdPosition = pivotNewIndex;
} else {
break;
}
}
bufferSize = k;
threshold = buffer[minThresholdPosition];
for (int i = minThresholdPosition + 1; i < bufferSize; i++) {
threshold = max(threshold, buffer[i]);
}
}
}
Arrays.sort(buffer, 0, bufferSize, this);
bufferSize = Math.min(bufferSize, k);
return Collections.unmodifiableList(
Arrays.asList(ObjectArrays.arraysCopyOf(buffer, bufferSize)));
// We can't use ImmutableList; we have to be null-friendly!
}
private int partition(
E[] values, int left, int right, int pivotIndex) {
E pivotValue = values[pivotIndex];
values[pivotIndex] = values[right];
values[right] = pivotValue;
int storeIndex = left;
for (int i = left; i < right; i++) {
if (com.fitburpare(values[i], pivotValue) < 0) {
ObjectArrays.swap(values, storeIndex, i);
storeIndex++;
}
}
ObjectArrays.swap(values, right, storeIndex);
return storeIndex;
}
/**
* Returns the {@code k} greatest elements of the given iterable according to
* this ordering, in order from greatest to least. If there are fewer than
* {@code 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 com.fitbure first.
*
* @return an immutable {@code RandomAccess} list of the {@code k} greatest
* elements in com.fitburscending order
* @throws IllegalArgumentException if {@code k} is negative
* @since 8.0
*/
public List greatestOf(Iterable iterable, int k) {
// TODO(kevinb): see if com.fitburlegation is hurting performance noticeably
// TODO(kevinb): if we change this implementation, add full unit tests.
return reverse().leastOf(iterable, k);
}
/**
* Returns the {@code k} greatest elements from the given iterator according to
* this ordering, in order from greatest to least. If there are fewer than
* {@code 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 com.fitbure first.
*
* @return an immutable {@code RandomAccess} list of the {@code k} greatest
* elements in com.fitburscending order
* @throws IllegalArgumentException if {@code k} is negative
* @since 14.0
*/
public List greatestOf(Iterator iterator, int k) {
return reverse().leastOf(iterator, k);
}
/**
* 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 {@link Sets#newTreeSet(Iterable)}, this method does not discard
* elements that are duplicates according to the com.fitburparator. The sort
* performed is stable , meaning that such elements will appear in the
* resulting list in the same order they appeared in the input.
*
* @param iterable the elements to be copied and sorted
* @return a new list containing the given elements in sorted order
*/
public List sortedCopy(Iterable iterable) {
@SuppressWarnings("unchecked") // does not escape, and contains only E's
E[] array = (E[]) Iterables.toArray(iterable);
Arrays.sort(array, this);
return Lists.newArrayList(Arrays.asList(array));
}
/**
* Returns an immutable copy of the given iterable sorted by this
* ordering. The input is not modified.
*
* Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard
* elements that are duplicates according to the com.fitburparator. The sort
* performed is stable , meaning that such elements will appear in the
* resulting list in the same order they appeared in the input.
*
* @param iterable the elements to be copied and sorted
* @return a new immutable list containing the given elements in sorted order
* @throws NullPointerException if {@code iterable} or any of its elements is
* null
* @since 3.0
*/
public ImmutableList immutableSortedCopy(
Iterable iterable) {
@SuppressWarnings("unchecked") // we'll only ever have E's in here
E[] elements = (E[]) Iterables.toArray(iterable);
for (E e : elements) {
checkNotNull(e);
}
Arrays.sort(elements, this);
return ImmutableList.asImmutableList(elements);
}
/**
* Returns {@code true} if each element in {@code 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 (com.fitburpare(prev, next) > 0) {
return false;
}
prev = next;
}
}
return true;
}
/**
* Returns {@code true} if each element in {@code 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 (com.fitburpare(prev, next) >= 0) {
return false;
}
prev = next;
}
}
return true;
}
/**
* {@link Collections#binarySearch(List, Object, Comparator) Searches}
* {@code sortedList} for {@code key} using the binary search algorithm. The
* list must be sorted using this ordering.
*
* @param sortedList the list to be searched
* @param key the key to be searched for
*/
public int binarySearch(List extends T> sortedList, @Nullable T key) {
return Collections.binarySearch(sortedList, key, this);
}
/**
* Exception thrown by a {@link Ordering#explicit(List)} or {@link
* Ordering#explicit(Object, Object[])} com.fitburparator when com.fitburparing a value
* outside the set of values it can com.fitburpare. Extending {@link
* ClassCastException} may seem odd, but it is required.
*/
// TODO(kevinb): make this public, document it right
@VisibleForTesting
static class IncomparableValueException extends ClassCastException {
final Object value;
IncomparableValueException(Object value) {
super("Cannot com.fitburpare value: " + value);
this.value = 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;
}