001/* 002 * Copyright (C) 2007 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.google.common.collect; 018 019import static com.google.common.base.Preconditions.checkNotNull; 020import static com.google.common.collect.CollectPreconditions.checkNonnegative; 021import static java.util.Arrays.asList; 022import static java.util.Arrays.sort; 023import static java.util.Collections.emptyList; 024import static java.util.Collections.sort; 025import static java.util.Collections.unmodifiableList; 026 027import com.google.common.annotations.GwtCompatible; 028import com.google.common.annotations.J2ktIncompatible; 029import com.google.common.annotations.VisibleForTesting; 030import com.google.common.base.Function; 031import java.util.ArrayList; 032import java.util.Arrays; 033import java.util.Collection; 034import java.util.Collections; 035import java.util.Comparator; 036import java.util.HashSet; 037import java.util.Iterator; 038import java.util.List; 039import java.util.Map.Entry; 040import java.util.NoSuchElementException; 041import java.util.SortedMap; 042import java.util.SortedSet; 043import java.util.TreeSet; 044import java.util.concurrent.ConcurrentMap; 045import java.util.concurrent.atomic.AtomicInteger; 046import javax.annotation.CheckForNull; 047import org.checkerframework.checker.nullness.qual.NonNull; 048import org.checkerframework.checker.nullness.qual.Nullable; 049 050/** 051 * A comparator, with additional methods to support common operations. This is an "enriched" version 052 * of {@code Comparator} for pre-Java-8 users, in the same sense that {@link FluentIterable} is an 053 * enriched {@link Iterable} for pre-Java-8 users. 054 * 055 * <h3>Three types of methods</h3> 056 * 057 * Like other fluent types, there are three types of methods present: methods for <i>acquiring</i>, 058 * <i>chaining</i>, and <i>using</i>. 059 * 060 * <h4>Acquiring</h4> 061 * 062 * <p>The common ways to get an instance of {@code Ordering} are: 063 * 064 * <ul> 065 * <li>Subclass it and implement {@link #compare} instead of implementing {@link Comparator} 066 * directly 067 * <li>Pass a <i>pre-existing</i> {@link Comparator} instance to {@link #from(Comparator)} 068 * <li>Use the natural ordering, {@link Ordering#natural} 069 * </ul> 070 * 071 * <h4>Chaining</h4> 072 * 073 * <p>Then you can use the <i>chaining</i> methods to get an altered version of that {@code 074 * Ordering}, including: 075 * 076 * <ul> 077 * <li>{@link #reverse} 078 * <li>{@link #compound(Comparator)} 079 * <li>{@link #onResultOf(Function)} 080 * <li>{@link #nullsFirst} / {@link #nullsLast} 081 * </ul> 082 * 083 * <h4>Using</h4> 084 * 085 * <p>Finally, use the resulting {@code Ordering} anywhere a {@link Comparator} is required, or use 086 * any of its special operations, such as: 087 * 088 * <ul> 089 * <li>{@link #immutableSortedCopy} 090 * <li>{@link #isOrdered} / {@link #isStrictlyOrdered} 091 * <li>{@link #min} / {@link #max} 092 * </ul> 093 * 094 * <h3>Understanding complex orderings</h3> 095 * 096 * <p>Complex chained orderings like the following example can be challenging to understand. 097 * 098 * <pre>{@code 099 * Ordering<Foo> ordering = 100 * Ordering.natural() 101 * .nullsFirst() 102 * .onResultOf(getBarFunction) 103 * .nullsLast(); 104 * }</pre> 105 * 106 * Note that each chaining method returns a new ordering instance which is backed by the previous 107 * instance, but has the chance to act on values <i>before</i> handing off to that backing instance. 108 * As a result, it usually helps to read chained ordering expressions <i>backwards</i>. For example, 109 * when {@code compare} is called on the above ordering: 110 * 111 * <ol> 112 * <li>First, if only one {@code Foo} is null, that null value is treated as <i>greater</i> 113 * <li>Next, non-null {@code Foo} values are passed to {@code getBarFunction} (we will be 114 * comparing {@code Bar} values from now on) 115 * <li>Next, if only one {@code Bar} is null, that null value is treated as <i>lesser</i> 116 * <li>Finally, natural ordering is used (i.e. the result of {@code Bar.compareTo(Bar)} is 117 * returned) 118 * </ol> 119 * 120 * <p>Alas, {@link #reverse} is a little different. As you read backwards through a chain and 121 * encounter a call to {@code reverse}, continue working backwards until a result is determined, and 122 * then reverse that result. 123 * 124 * <h3>Additional notes</h3> 125 * 126 * <p>Except as noted, the orderings returned by the factory methods of this class are serializable 127 * if and only if the provided instances that back them are. For example, if {@code ordering} and 128 * {@code function} can themselves be serialized, then {@code ordering.onResultOf(function)} can as 129 * well. 130 * 131 * <h3>Java 8+ users</h3> 132 * 133 * <p>If you are using Java 8+, this class is now obsolete. Most of its functionality is now 134 * provided by {@link java.util.stream.Stream Stream} and by {@link Comparator} itself, and the rest 135 * can now be found as static methods in our new {@link Comparators} class. See each method below 136 * for further instructions. Whenever possible, you should change any references of type {@code 137 * Ordering} to be of type {@code Comparator} instead. However, at this time we have no plan to 138 * <i>deprecate</i> this class. 139 * 140 * <p>Many replacements involve adopting {@code Stream}, and these changes can sometimes make your 141 * code verbose. Whenever following this advice, you should check whether {@code Stream} could be 142 * adopted more comprehensively in your code; the end result may be quite a bit simpler. 143 * 144 * <h3>See also</h3> 145 * 146 * <p>See the Guava User Guide article on <a href= 147 * "https://github.com/google/guava/wiki/OrderingExplained">{@code Ordering}</a>. 148 * 149 * @author Jesse Wilson 150 * @author Kevin Bourrillion 151 * @since 2.0 152 */ 153@GwtCompatible 154@ElementTypesAreNonnullByDefault 155public abstract class Ordering<T extends @Nullable Object> implements Comparator<T> { 156 // Natural order 157 158 /** 159 * Returns a serializable ordering that uses the natural order of the values. The ordering throws 160 * a {@link NullPointerException} when passed a null parameter. 161 * 162 * <p>The type specification is {@code <C extends Comparable>}, instead of the technically correct 163 * {@code <C extends Comparable<? super C>>}, to support legacy types from before Java 5. 164 * 165 * <p><b>Java 8+ users:</b> use {@link Comparator#naturalOrder} instead. 166 */ 167 @GwtCompatible(serializable = true) 168 @SuppressWarnings({"unchecked", "rawtypes"}) 169 // TODO(kevinb): right way to explain this?? 170 // plus https://github.com/google/guava/issues/989 171 public static <C extends Comparable> Ordering<C> natural() { 172 return (Ordering<C>) NaturalOrdering.INSTANCE; 173 } 174 175 // Static factories 176 177 /** 178 * Returns an ordering based on an <i>existing</i> comparator instance. Note that it is 179 * unnecessary to create a <i>new</i> anonymous inner class implementing {@code Comparator} just 180 * to pass it in here. Instead, simply subclass {@code Ordering} and implement its {@code compare} 181 * method directly. 182 * 183 * <p>The returned object is serializable if {@code comparator} is serializable. 184 * 185 * <p><b>Java 8+ users:</b> this class is now obsolete as explained in the class documentation, so 186 * there is no need to use this method. 187 * 188 * @param comparator the comparator that defines the order 189 * @return comparator itself if it is already an {@code Ordering}; otherwise an ordering that 190 * wraps that comparator 191 */ 192 @GwtCompatible(serializable = true) 193 public static <T extends @Nullable Object> Ordering<T> from(Comparator<T> comparator) { 194 return (comparator instanceof Ordering) 195 ? (Ordering<T>) comparator 196 : new ComparatorOrdering<T>(comparator); 197 } 198 199 /** 200 * Simply returns its argument. 201 * 202 * @deprecated no need to use this 203 */ 204 @GwtCompatible(serializable = true) 205 @Deprecated 206 public static <T extends @Nullable Object> Ordering<T> from(Ordering<T> ordering) { 207 return checkNotNull(ordering); 208 } 209 210 /** 211 * Returns an ordering that compares objects according to the order in which they appear in the 212 * given list. Only objects present in the list (according to {@link Object#equals}) may be 213 * compared. This comparator imposes a "partial ordering" over the type {@code T}. Subsequent 214 * changes to the {@code valuesInOrder} list will have no effect on the returned comparator. Null 215 * values in the list are not supported. 216 * 217 * <p>The returned comparator throws a {@link ClassCastException} when it receives an input 218 * parameter that isn't among the provided values. 219 * 220 * <p>The generated comparator is serializable if all the provided values are serializable. 221 * 222 * @param valuesInOrder the values that the returned comparator will be able to compare, in the 223 * order the comparator should induce 224 * @return the comparator described above 225 * @throws NullPointerException if any of the provided values is null 226 * @throws IllegalArgumentException if {@code valuesInOrder} contains any duplicate values 227 * (according to {@link Object#equals}) 228 */ 229 // TODO(kevinb): provide replacement 230 @GwtCompatible(serializable = true) 231 public static <T> Ordering<T> explicit(List<T> valuesInOrder) { 232 return new ExplicitOrdering<>(valuesInOrder); 233 } 234 235 /** 236 * Returns an ordering that compares objects according to the order in which they are given to 237 * this method. Only objects present in the argument list (according to {@link Object#equals}) may 238 * be compared. This comparator imposes a "partial ordering" over the type {@code T}. Null values 239 * in the argument list are not supported. 240 * 241 * <p>The returned comparator throws a {@link ClassCastException} when it receives an input 242 * parameter that isn't among the provided values. 243 * 244 * <p>The generated comparator is serializable if all the provided values are serializable. 245 * 246 * @param leastValue the value which the returned comparator should consider the "least" of all 247 * values 248 * @param remainingValuesInOrder the rest of the values that the returned comparator will be able 249 * to compare, in the order the comparator should follow 250 * @return the comparator described above 251 * @throws NullPointerException if any of the provided values is null 252 * @throws IllegalArgumentException if any duplicate values (according to {@link 253 * Object#equals(Object)}) are present among the method arguments 254 */ 255 // TODO(kevinb): provide replacement 256 @GwtCompatible(serializable = true) 257 public static <T> Ordering<T> explicit(T leastValue, T... remainingValuesInOrder) { 258 return explicit(Lists.asList(leastValue, remainingValuesInOrder)); 259 } 260 261 // Ordering<Object> singletons 262 263 /** 264 * Returns an ordering which treats all values as equal, indicating "no ordering." Passing this 265 * ordering to any <i>stable</i> sort algorithm results in no change to the order of elements. 266 * Note especially that {@link #sortedCopy} and {@link #immutableSortedCopy} are stable, and in 267 * the returned instance these are implemented by simply copying the source list. 268 * 269 * <p>Example: 270 * 271 * <pre>{@code 272 * Ordering.allEqual().nullsLast().sortedCopy( 273 * asList(t, null, e, s, null, t, null)) 274 * }</pre> 275 * 276 * <p>Assuming {@code t}, {@code e} and {@code s} are non-null, this returns {@code [t, e, s, t, 277 * null, null, null]} regardless of the true comparison order of those three values (which might 278 * not even implement {@link Comparable} at all). 279 * 280 * <p><b>Warning:</b> by definition, this comparator is not <i>consistent with equals</i> (as 281 * defined {@linkplain Comparator here}). Avoid its use in APIs, such as {@link 282 * TreeSet#TreeSet(Comparator)}, where such consistency is expected. 283 * 284 * <p>The returned comparator is serializable. 285 * 286 * <p><b>Java 8+ users:</b> Use the lambda expression {@code (a, b) -> 0} instead (in certain 287 * cases you may need to cast that to {@code Comparator<YourType>}). 288 * 289 * @since 13.0 290 */ 291 @GwtCompatible(serializable = true) 292 public static Ordering<@Nullable Object> allEqual() { 293 return AllEqualOrdering.INSTANCE; 294 } 295 296 /** 297 * Returns an ordering that compares objects by the natural ordering of their string 298 * representations as returned by {@code toString()}. It does not support null values. 299 * 300 * <p>The comparator is serializable. 301 * 302 * <p><b>Java 8+ users:</b> Use {@code Comparator.comparing(Object::toString)} instead. 303 */ 304 @GwtCompatible(serializable = true) 305 public static Ordering<Object> usingToString() { 306 return UsingToStringOrdering.INSTANCE; 307 } 308 309 /** 310 * Returns an arbitrary ordering over all objects, for which {@code compare(a, b) == 0} implies 311 * {@code a == b} (identity equality). There is no meaning whatsoever to the order imposed, but it 312 * is constant for the life of the VM. 313 * 314 * <p>Because the ordering is identity-based, it is not "consistent with {@link 315 * Object#equals(Object)}" as defined by {@link Comparator}. Use caution when building a {@link 316 * SortedSet} or {@link SortedMap} from it, as the resulting collection will not behave exactly 317 * according to spec. 318 * 319 * <p>This ordering is not serializable, as its implementation relies on {@link 320 * System#identityHashCode(Object)}, so its behavior cannot be preserved across serialization. 321 * 322 * @since 2.0 323 */ 324 // TODO(kevinb): copy to Comparators, etc. 325 @J2ktIncompatible // MapMaker 326 public static Ordering<@Nullable Object> arbitrary() { 327 return ArbitraryOrderingHolder.ARBITRARY_ORDERING; 328 } 329 330 @J2ktIncompatible // MapMaker 331 private static class ArbitraryOrderingHolder { 332 static final Ordering<@Nullable Object> ARBITRARY_ORDERING = new ArbitraryOrdering(); 333 } 334 335 @J2ktIncompatible // MapMaker 336 @VisibleForTesting 337 static class ArbitraryOrdering extends Ordering<@Nullable Object> { 338 339 private final AtomicInteger counter = new AtomicInteger(0); 340 private final ConcurrentMap<Object, Integer> uids = 341 Platform.tryWeakKeys(new MapMaker()).makeMap(); 342 343 private Integer getUid(Object obj) { 344 Integer uid = uids.get(obj); 345 if (uid == null) { 346 // One or more integer values could be skipped in the event of a race 347 // to generate a UID for the same object from multiple threads, but 348 // that shouldn't be a problem. 349 uid = counter.getAndIncrement(); 350 Integer alreadySet = uids.putIfAbsent(obj, uid); 351 if (alreadySet != null) { 352 uid = alreadySet; 353 } 354 } 355 return uid; 356 } 357 358 @Override 359 public int compare(@CheckForNull Object left, @CheckForNull Object right) { 360 if (left == right) { 361 return 0; 362 } else if (left == null) { 363 return -1; 364 } else if (right == null) { 365 return 1; 366 } 367 int leftCode = identityHashCode(left); 368 int rightCode = identityHashCode(right); 369 if (leftCode != rightCode) { 370 return leftCode < rightCode ? -1 : 1; 371 } 372 373 // identityHashCode collision (rare, but not as rare as you'd think) 374 int result = getUid(left).compareTo(getUid(right)); 375 if (result == 0) { 376 throw new AssertionError(); // extremely, extremely unlikely. 377 } 378 return result; 379 } 380 381 @Override 382 public String toString() { 383 return "Ordering.arbitrary()"; 384 } 385 386 /* 387 * We need to be able to mock identityHashCode() calls for tests, because it 388 * can take 1-10 seconds to find colliding objects. Mocking frameworks that 389 * can do magic to mock static method calls still can't do so for a system 390 * class, so we need the indirection. In production, Hotspot should still 391 * recognize that the call is 1-morphic and should still be willing to 392 * inline it if necessary. 393 */ 394 int identityHashCode(Object object) { 395 return System.identityHashCode(object); 396 } 397 } 398 399 // Constructor 400 401 /** 402 * Constructs a new instance of this class (only invokable by the subclass constructor, typically 403 * implicit). 404 */ 405 protected Ordering() {} 406 407 // Instance-based factories (and any static equivalents) 408 409 /** 410 * Returns the reverse of this ordering; the {@code Ordering} equivalent to {@link 411 * Collections#reverseOrder(Comparator)}. 412 * 413 * <p><b>Java 8+ users:</b> Use {@code thisComparator.reversed()} instead. 414 */ 415 // type parameter <S> lets us avoid the extra <String> in statements like: 416 // Ordering<String> o = Ordering.<String>natural().reverse(); 417 @GwtCompatible(serializable = true) 418 public <S extends T> Ordering<S> reverse() { 419 return new ReverseOrdering<>(this); 420 } 421 422 /** 423 * Returns an ordering that treats {@code null} as less than all other values and uses {@code 424 * this} to compare non-null values. 425 * 426 * <p>The returned object is serializable if this object is serializable. 427 * 428 * <p><b>Java 8+ users:</b> Use {@code Comparator.nullsFirst(thisComparator)} instead. 429 */ 430 // type parameter <S> lets us avoid the extra <String> in statements like: 431 // Ordering<String> o = Ordering.<String>natural().nullsFirst(); 432 @GwtCompatible(serializable = true) 433 public <S extends T> Ordering<@Nullable S> nullsFirst() { 434 return new NullsFirstOrdering<S>(this); 435 } 436 437 /** 438 * Returns an ordering that treats {@code null} as greater than all other values and uses this 439 * ordering to compare non-null values. 440 * 441 * <p>The returned object is serializable if this object is serializable. 442 * 443 * <p><b>Java 8+ users:</b> Use {@code Comparator.nullsLast(thisComparator)} instead. 444 */ 445 // type parameter <S> lets us avoid the extra <String> in statements like: 446 // Ordering<String> o = Ordering.<String>natural().nullsLast(); 447 @GwtCompatible(serializable = true) 448 public <S extends T> Ordering<@Nullable S> nullsLast() { 449 return new NullsLastOrdering<S>(this); 450 } 451 452 /** 453 * Returns a new ordering on {@code F} which orders elements by first applying a function to them, 454 * then comparing those results using {@code this}. For example, to compare objects by their 455 * string forms, in a case-insensitive manner, use: 456 * 457 * <pre>{@code 458 * Ordering.from(String.CASE_INSENSITIVE_ORDER) 459 * .onResultOf(Functions.toStringFunction()) 460 * }</pre> 461 * 462 * <p><b>Java 8+ users:</b> Use {@code Comparator.comparing(function, thisComparator)} instead 463 * (you can omit the comparator if it is the natural order). 464 */ 465 @GwtCompatible(serializable = true) 466 public <F extends @Nullable Object> Ordering<F> onResultOf(Function<F, ? extends T> function) { 467 return new ByFunctionOrdering<>(function, this); 468 } 469 470 <T2 extends T> Ordering<Entry<T2, ?>> onKeys() { 471 return onResultOf(Maps.<T2>keyFunction()); 472 } 473 474 /** 475 * Returns an ordering which first uses the ordering {@code this}, but which in the event of a 476 * "tie", then delegates to {@code secondaryComparator}. For example, to sort a bug list first by 477 * status and second by priority, you might use {@code byStatus.compound(byPriority)}. For a 478 * compound ordering with three or more components, simply chain multiple calls to this method. 479 * 480 * <p>An ordering produced by this method, or a chain of calls to this method, is equivalent to 481 * one created using {@link Ordering#compound(Iterable)} on the same component comparators. 482 * 483 * <p>The returned object is serializable if this object and {@code secondaryComparator} are both 484 * serializable. 485 * 486 * <p><b>Java 8+ users:</b> Use {@code thisComparator.thenComparing(secondaryComparator)} instead. 487 * Depending on what {@code secondaryComparator} is, one of the other overloads of {@code 488 * thenComparing} may be even more useful. 489 */ 490 @GwtCompatible(serializable = true) 491 public <U extends T> Ordering<U> compound(Comparator<? super U> secondaryComparator) { 492 return new CompoundOrdering<>(this, checkNotNull(secondaryComparator)); 493 } 494 495 /** 496 * Returns an ordering which tries each given comparator in order until a non-zero result is 497 * found, returning that result, and returning zero only if all comparators return zero. The 498 * returned ordering is based on the state of the {@code comparators} iterable at the time it was 499 * provided to this method. 500 * 501 * <p>The returned ordering is equivalent to that produced using {@code 502 * Ordering.from(comp1).compound(comp2).compound(comp3) . . .}. 503 * 504 * <p>The returned object is serializable if each of the {@code comparators} is serializable. 505 * 506 * <p><b>Warning:</b> Supplying an argument with undefined iteration order, such as a {@link 507 * HashSet}, will produce non-deterministic results. 508 * 509 * <p><b>Java 8+ users:</b> Use a chain of calls to {@link Comparator#thenComparing(Comparator)}, 510 * or {@code comparatorCollection.stream().reduce(Comparator::thenComparing).get()} (if the 511 * collection might be empty, also provide a default comparator as the {@code identity} parameter 512 * to {@code reduce}). 513 * 514 * @param comparators the comparators to try in order 515 */ 516 @GwtCompatible(serializable = true) 517 public static <T extends @Nullable Object> Ordering<T> compound( 518 Iterable<? extends Comparator<? super T>> comparators) { 519 return new CompoundOrdering<>(comparators); 520 } 521 522 /** 523 * Returns a new ordering which sorts iterables by comparing corresponding elements pairwise until 524 * a nonzero result is found; imposes "dictionary order". If the end of one iterable is reached, 525 * but not the other, the shorter iterable is considered to be less than the longer one. For 526 * example, a lexicographical natural ordering over integers considers {@code [] < [1] < [1, 1] < 527 * [1, 2] < [2]}. 528 * 529 * <p>Note that {@code ordering.lexicographical().reverse()} is not equivalent to {@code 530 * ordering.reverse().lexicographical()} (consider how each would order {@code [1]} and {@code [1, 531 * 1]}). 532 * 533 * <p><b>Java 8+ users:</b> Use {@link Comparators#lexicographical(Comparator)} instead. 534 * 535 * @since 2.0 536 */ 537 @GwtCompatible(serializable = true) 538 // type parameter <S> lets us avoid the extra <String> in statements like: 539 // Ordering<Iterable<String>> o = 540 // Ordering.<String>natural().lexicographical(); 541 public <S extends T> Ordering<Iterable<S>> lexicographical() { 542 /* 543 * Note that technically the returned ordering should be capable of 544 * handling not just {@code Iterable<S>} instances, but also any {@code 545 * Iterable<? extends S>}. However, the need for this comes up so rarely 546 * that it doesn't justify making everyone else deal with the very ugly 547 * wildcard. 548 */ 549 return new LexicographicalOrdering<S>(this); 550 } 551 552 // Regular instance methods 553 554 @Override 555 public abstract int compare(@ParametricNullness T left, @ParametricNullness T right); 556 557 /** 558 * Returns the least of the specified values according to this ordering. If there are multiple 559 * least values, the first of those is returned. The iterator will be left exhausted: its {@code 560 * hasNext()} method will return {@code false}. 561 * 562 * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterator).min(thisComparator).get()} instead 563 * (but note that it does not guarantee which tied minimum element is returned). 564 * 565 * @param iterator the iterator whose minimum element is to be determined 566 * @throws NoSuchElementException if {@code iterator} is empty 567 * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this 568 * ordering. 569 * @since 11.0 570 */ 571 @ParametricNullness 572 public <E extends T> E min(Iterator<E> iterator) { 573 // let this throw NoSuchElementException as necessary 574 E minSoFar = iterator.next(); 575 576 while (iterator.hasNext()) { 577 minSoFar = this.<E>min(minSoFar, iterator.next()); 578 } 579 580 return minSoFar; 581 } 582 583 /** 584 * Returns the least of the specified values according to this ordering. If there are multiple 585 * least values, the first of those is returned. 586 * 587 * <p><b>Java 8+ users:</b> If {@code iterable} is a {@link Collection}, use {@code 588 * Collections.min(collection, thisComparator)} instead. Otherwise, use {@code 589 * Streams.stream(iterable).min(thisComparator).get()} instead. Note that these alternatives do 590 * not guarantee which tied minimum element is returned. 591 * 592 * @param iterable the iterable whose minimum element is to be determined 593 * @throws NoSuchElementException if {@code iterable} is empty 594 * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this 595 * ordering. 596 */ 597 @ParametricNullness 598 public <E extends T> E min(Iterable<E> iterable) { 599 return min(iterable.iterator()); 600 } 601 602 /** 603 * Returns the lesser of the two values according to this ordering. If the values compare as 0, 604 * the first is returned. 605 * 606 * <p><b>Implementation note:</b> this method is invoked by the default implementations of the 607 * other {@code min} overloads, so overriding it will affect their behavior. 608 * 609 * <p><b>Note:</b> Consider using {@code Comparators.min(a, b, thisComparator)} instead. If {@code 610 * thisComparator} is {@link Ordering#natural}, then use {@code Comparators.min(a, b)}. 611 * 612 * @param a value to compare, returned if less than or equal to b. 613 * @param b value to compare. 614 * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this 615 * ordering. 616 */ 617 @ParametricNullness 618 public <E extends T> E min(@ParametricNullness E a, @ParametricNullness E b) { 619 return (compare(a, b) <= 0) ? a : b; 620 } 621 622 /** 623 * Returns the least of the specified values according to this ordering. If there are multiple 624 * least values, the first of those is returned. 625 * 626 * <p><b>Java 8+ users:</b> Use {@code Collections.min(Arrays.asList(a, b, c...), thisComparator)} 627 * instead (but note that it does not guarantee which tied minimum element is returned). 628 * 629 * @param a value to compare, returned if less than or equal to the rest. 630 * @param b value to compare 631 * @param c value to compare 632 * @param rest values to compare 633 * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this 634 * ordering. 635 */ 636 @ParametricNullness 637 public <E extends T> E min( 638 @ParametricNullness E a, @ParametricNullness E b, @ParametricNullness E c, E... rest) { 639 E minSoFar = min(min(a, b), c); 640 641 for (E r : rest) { 642 minSoFar = min(minSoFar, r); 643 } 644 645 return minSoFar; 646 } 647 648 /** 649 * Returns the greatest of the specified values according to this ordering. If there are multiple 650 * greatest values, the first of those is returned. The iterator will be left exhausted: its 651 * {@code hasNext()} method will return {@code false}. 652 * 653 * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterator).max(thisComparator).get()} instead 654 * (but note that it does not guarantee which tied maximum element is returned). 655 * 656 * @param iterator the iterator whose maximum element is to be determined 657 * @throws NoSuchElementException if {@code iterator} is empty 658 * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this 659 * ordering. 660 * @since 11.0 661 */ 662 @ParametricNullness 663 public <E extends T> E max(Iterator<E> iterator) { 664 // let this throw NoSuchElementException as necessary 665 E maxSoFar = iterator.next(); 666 667 while (iterator.hasNext()) { 668 maxSoFar = this.<E>max(maxSoFar, iterator.next()); 669 } 670 671 return maxSoFar; 672 } 673 674 /** 675 * Returns the greatest of the specified values according to this ordering. If there are multiple 676 * greatest values, the first of those is returned. 677 * 678 * <p><b>Java 8+ users:</b> If {@code iterable} is a {@link Collection}, use {@code 679 * Collections.max(collection, thisComparator)} instead. Otherwise, use {@code 680 * Streams.stream(iterable).max(thisComparator).get()} instead. Note that these alternatives do 681 * not guarantee which tied maximum element is returned. 682 * 683 * @param iterable the iterable whose maximum element is to be determined 684 * @throws NoSuchElementException if {@code iterable} is empty 685 * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this 686 * ordering. 687 */ 688 @ParametricNullness 689 public <E extends T> E max(Iterable<E> iterable) { 690 return max(iterable.iterator()); 691 } 692 693 /** 694 * Returns the greater of the two values according to this ordering. If the values compare as 0, 695 * the first is returned. 696 * 697 * <p><b>Implementation note:</b> this method is invoked by the default implementations of the 698 * other {@code max} overloads, so overriding it will affect their behavior. 699 * 700 * <p><b>Note:</b> Consider using {@code Comparators.max(a, b, thisComparator)} instead. If {@code 701 * thisComparator} is {@link Ordering#natural}, then use {@code Comparators.max(a, b)}. 702 * 703 * @param a value to compare, returned if greater than or equal to b. 704 * @param b value to compare. 705 * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this 706 * ordering. 707 */ 708 @ParametricNullness 709 public <E extends T> E max(@ParametricNullness E a, @ParametricNullness E b) { 710 return (compare(a, b) >= 0) ? a : b; 711 } 712 713 /** 714 * Returns the greatest of the specified values according to this ordering. If there are multiple 715 * greatest values, the first of those is returned. 716 * 717 * <p><b>Java 8+ users:</b> Use {@code Collections.max(Arrays.asList(a, b, c...), thisComparator)} 718 * instead (but note that it does not guarantee which tied maximum element is returned). 719 * 720 * @param a value to compare, returned if greater than or equal to the rest. 721 * @param b value to compare 722 * @param c value to compare 723 * @param rest values to compare 724 * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this 725 * ordering. 726 */ 727 @ParametricNullness 728 public <E extends T> E max( 729 @ParametricNullness E a, @ParametricNullness E b, @ParametricNullness E c, E... rest) { 730 E maxSoFar = max(max(a, b), c); 731 732 for (E r : rest) { 733 maxSoFar = max(maxSoFar, r); 734 } 735 736 return maxSoFar; 737 } 738 739 /** 740 * Returns the {@code k} least elements of the given iterable according to this ordering, in order 741 * from least to greatest. If there are fewer than {@code k} elements present, all will be 742 * included. 743 * 744 * <p>The implementation does not necessarily use a <i>stable</i> sorting algorithm; when multiple 745 * elements are equivalent, it is undefined which will come first. 746 * 747 * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterable).collect(Comparators.least(k, 748 * thisComparator))} instead. 749 * 750 * @return an immutable {@code RandomAccess} list of the {@code k} least elements in ascending 751 * order 752 * @throws IllegalArgumentException if {@code k} is negative 753 * @since 8.0 754 */ 755 public <E extends T> List<E> leastOf(Iterable<E> iterable, int k) { 756 if (iterable instanceof Collection) { 757 Collection<E> collection = (Collection<E>) iterable; 758 if (collection.size() <= 2L * k) { 759 // In this case, just dumping the collection to an array and sorting is 760 // faster than using the implementation for Iterator, which is 761 // specialized for k much smaller than n. 762 763 @SuppressWarnings("unchecked") // c only contains E's and doesn't escape 764 E[] array = (E[]) collection.toArray(); 765 sort(array, this); 766 if (array.length > k) { 767 array = Arrays.copyOf(array, k); 768 } 769 return unmodifiableList(asList(array)); 770 } 771 } 772 return leastOf(iterable.iterator(), k); 773 } 774 775 /** 776 * Returns the {@code k} least elements from the given iterator according to this ordering, in 777 * order from least to greatest. If there are fewer than {@code k} elements present, all will be 778 * included. 779 * 780 * <p>The implementation does not necessarily use a <i>stable</i> sorting algorithm; when multiple 781 * elements are equivalent, it is undefined which will come first. 782 * 783 * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterator).collect(Comparators.least(k, 784 * thisComparator))} instead. 785 * 786 * @return an immutable {@code RandomAccess} list of the {@code k} least elements in ascending 787 * order 788 * @throws IllegalArgumentException if {@code k} is negative 789 * @since 14.0 790 */ 791 public <E extends T> List<E> leastOf(Iterator<E> iterator, int k) { 792 checkNotNull(iterator); 793 checkNonnegative(k, "k"); 794 795 if (k == 0 || !iterator.hasNext()) { 796 return emptyList(); 797 } else if (k >= Integer.MAX_VALUE / 2) { 798 // k is really large; just do a straightforward sorted-copy-and-sublist 799 ArrayList<E> list = Lists.newArrayList(iterator); 800 sort(list, this); 801 if (list.size() > k) { 802 list.subList(k, list.size()).clear(); 803 } 804 list.trimToSize(); 805 return unmodifiableList(list); 806 } else { 807 TopKSelector<E> selector = TopKSelector.least(k, this); 808 selector.offerAll(iterator); 809 return selector.topK(); 810 } 811 } 812 813 /** 814 * Returns the {@code k} greatest elements of the given iterable according to this ordering, in 815 * order from greatest to least. If there are fewer than {@code k} elements present, all will be 816 * included. 817 * 818 * <p>The implementation does not necessarily use a <i>stable</i> sorting algorithm; when multiple 819 * elements are equivalent, it is undefined which will come first. 820 * 821 * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterable).collect(Comparators.greatest(k, 822 * thisComparator))} instead. 823 * 824 * @return an immutable {@code RandomAccess} list of the {@code k} greatest elements in 825 * <i>descending order</i> 826 * @throws IllegalArgumentException if {@code k} is negative 827 * @since 8.0 828 */ 829 public <E extends T> List<E> greatestOf(Iterable<E> iterable, int k) { 830 // TODO(kevinb): see if delegation is hurting performance noticeably 831 // TODO(kevinb): if we change this implementation, add full unit tests. 832 return this.<E>reverse().leastOf(iterable, k); 833 } 834 835 /** 836 * Returns the {@code k} greatest elements from the given iterator according to this ordering, in 837 * order from greatest to least. If there are fewer than {@code k} elements present, all will be 838 * included. 839 * 840 * <p>The implementation does not necessarily use a <i>stable</i> sorting algorithm; when multiple 841 * elements are equivalent, it is undefined which will come first. 842 * 843 * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterator).collect(Comparators.greatest(k, 844 * thisComparator))} instead. 845 * 846 * @return an immutable {@code RandomAccess} list of the {@code k} greatest elements in 847 * <i>descending order</i> 848 * @throws IllegalArgumentException if {@code k} is negative 849 * @since 14.0 850 */ 851 public <E extends T> List<E> greatestOf(Iterator<E> iterator, int k) { 852 return this.<E>reverse().leastOf(iterator, k); 853 } 854 855 /** 856 * Returns a <b>mutable</b> list containing {@code elements} sorted by this ordering; use this 857 * only when the resulting list may need further modification, or may contain {@code null}. The 858 * input is not modified. The returned list is serializable and has random access. 859 * 860 * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard elements that are 861 * duplicates according to the comparator. The sort performed is <i>stable</i>, meaning that such 862 * elements will appear in the returned list in the same order they appeared in {@code elements}. 863 * 864 * <p><b>Performance note:</b> According to our 865 * benchmarking 866 * on Open JDK 7, {@link #immutableSortedCopy} generally performs better (in both time and space) 867 * than this method, and this method in turn generally performs better than copying the list and 868 * calling {@link Collections#sort(List)}. 869 */ 870 // TODO(kevinb): rerun benchmarks including new options 871 public <E extends T> List<E> sortedCopy(Iterable<E> elements) { 872 @SuppressWarnings("unchecked") // does not escape, and contains only E's 873 E[] array = (E[]) Iterables.toArray(elements); 874 sort(array, this); 875 return Lists.newArrayList(asList(array)); 876 } 877 878 /** 879 * Returns an <b>immutable</b> list containing {@code elements} sorted by this ordering. The input 880 * is not modified. 881 * 882 * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard elements that are 883 * duplicates according to the comparator. The sort performed is <i>stable</i>, meaning that such 884 * elements will appear in the returned list in the same order they appeared in {@code elements}. 885 * 886 * <p><b>Performance note:</b> According to our 887 * benchmarking 888 * on Open JDK 7, this method is the most efficient way to make a sorted copy of a collection. 889 * 890 * @throws NullPointerException if any element of {@code elements} is {@code null} 891 * @since 3.0 892 */ 893 // TODO(kevinb): rerun benchmarks including new options 894 public <E extends @NonNull T> ImmutableList<E> immutableSortedCopy(Iterable<E> elements) { 895 return ImmutableList.sortedCopyOf(this, elements); 896 } 897 898 /** 899 * Returns {@code true} if each element in {@code iterable} after the first is greater than or 900 * equal to the element that preceded it, according to this ordering. Note that this is always 901 * true when the iterable has fewer than two elements. 902 * 903 * <p><b>Java 8+ users:</b> Use the equivalent {@link Comparators#isInOrder(Iterable, Comparator)} 904 * instead, since the rest of {@code Ordering} is mostly obsolete (as explained in the class 905 * documentation). 906 */ 907 public boolean isOrdered(Iterable<? extends T> iterable) { 908 Iterator<? extends T> it = iterable.iterator(); 909 if (it.hasNext()) { 910 T prev = it.next(); 911 while (it.hasNext()) { 912 T next = it.next(); 913 if (compare(prev, next) > 0) { 914 return false; 915 } 916 prev = next; 917 } 918 } 919 return true; 920 } 921 922 /** 923 * Returns {@code true} if each element in {@code iterable} after the first is <i>strictly</i> 924 * greater than the element that preceded it, according to this ordering. Note that this is always 925 * true when the iterable has fewer than two elements. 926 * 927 * <p><b>Java 8+ users:</b> Use the equivalent {@link Comparators#isInStrictOrder(Iterable, 928 * Comparator)} instead, since the rest of {@code Ordering} is mostly obsolete (as explained in 929 * the class documentation). 930 */ 931 public boolean isStrictlyOrdered(Iterable<? extends T> iterable) { 932 Iterator<? extends T> it = iterable.iterator(); 933 if (it.hasNext()) { 934 T prev = it.next(); 935 while (it.hasNext()) { 936 T next = it.next(); 937 if (compare(prev, next) >= 0) { 938 return false; 939 } 940 prev = next; 941 } 942 } 943 return true; 944 } 945 946 /** 947 * {@link Collections#binarySearch(List, Object, Comparator) Searches} {@code sortedList} for 948 * {@code key} using the binary search algorithm. The list must be sorted using this ordering. 949 * 950 * @param sortedList the list to be searched 951 * @param key the key to be searched for 952 * @deprecated Use {@link Collections#binarySearch(List, Object, Comparator)} directly. 953 */ 954 @Deprecated 955 public int binarySearch( 956 List<? extends T> sortedList, @ParametricNullness T key) { 957 return Collections.binarySearch(sortedList, key, this); 958 } 959 960 /** 961 * Exception thrown by a {@link Ordering#explicit(List)} or {@link Ordering#explicit(Object, 962 * Object[])} comparator when comparing a value outside the set of values it can compare. 963 * Extending {@link ClassCastException} may seem odd, but it is required. 964 */ 965 static class IncomparableValueException extends ClassCastException { 966 final Object value; 967 968 IncomparableValueException(Object value) { 969 super("Cannot compare value: " + value); 970 this.value = value; 971 } 972 973 private static final long serialVersionUID = 0; 974 } 975 976 // Never make these public 977 static final int LEFT_IS_GREATER = 1; 978 static final int RIGHT_IS_GREATER = -1; 979}