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