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