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