1 /* 2 * Copyright (C) 2007 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.common.collect; 18 19 import static com.google.common.base.Preconditions.checkNotNull; 20 import static com.google.common.collect.CollectPreconditions.checkNonnegative; 21 22 import com.google.common.annotations.GwtCompatible; 23 import com.google.common.annotations.VisibleForTesting; 24 import com.google.common.base.Function; 25 26 import java.util.ArrayList; 27 import java.util.Arrays; 28 import java.util.Collection; 29 import java.util.Collections; 30 import java.util.Comparator; 31 import java.util.HashSet; 32 import java.util.Iterator; 33 import java.util.List; 34 import java.util.Map; 35 import java.util.NoSuchElementException; 36 import java.util.SortedMap; 37 import java.util.SortedSet; 38 import java.util.TreeSet; 39 import java.util.concurrent.atomic.AtomicInteger; 40 41 import javax.annotation.Nullable; 42 43 /** 44 * A comparator, with additional methods to support common operations. This is 45 * an "enriched" version of {@code Comparator}, in the same sense that {@link 46 * FluentIterable} is an enriched {@link Iterable}. 47 * 48 * <p>The common ways to get an instance of {@code Ordering} are: 49 * 50 * <ul> 51 * <li>Subclass it and implement {@link #compare} instead of implementing 52 * {@link Comparator} directly 53 * <li>Pass a <i>pre-existing</i> {@link Comparator} instance to {@link 54 * #from(Comparator)} 55 * <li>Use the natural ordering, {@link Ordering#natural} 56 * </ul> 57 * 58 * <p>Then you can use the <i>chaining</i> methods to get an altered version of 59 * that {@code Ordering}, including: 60 * 61 * <ul> 62 * <li>{@link #reverse} 63 * <li>{@link #compound(Comparator)} 64 * <li>{@link #onResultOf(Function)} 65 * <li>{@link #nullsFirst} / {@link #nullsLast} 66 * </ul> 67 * 68 * <p>Finally, use the resulting {@code Ordering} anywhere a {@link Comparator} 69 * is required, or use any of its special operations, such as:</p> 70 * 71 * <ul> 72 * <li>{@link #immutableSortedCopy} 73 * <li>{@link #isOrdered} / {@link #isStrictlyOrdered} 74 * <li>{@link #min} / {@link #max} 75 * </ul> 76 * 77 * <p>Except as noted, the orderings returned by the factory methods of this 78 * class are serializable if and only if the provided instances that back them 79 * are. For example, if {@code ordering} and {@code function} can themselves be 80 * serialized, then {@code ordering.onResultOf(function)} can as well. 81 * 82 * <p>See the Guava User Guide article on <a href= 83 * "http://code.google.com/p/guava-libraries/wiki/OrderingExplained"> 84 * {@code Ordering}</a>. 85 * 86 * @author Jesse Wilson 87 * @author Kevin Bourrillion 88 * @since 2.0 (imported from Google Collections Library) 89 */ 90 @GwtCompatible 91 public abstract class Ordering<T> implements Comparator<T> { 92 // Natural order 93 94 /** 95 * Returns a serializable ordering that uses the natural order of the values. 96 * The ordering throws a {@link NullPointerException} when passed a null 97 * parameter. 98 * 99 * <p>The type specification is {@code <C extends Comparable>}, instead of 100 * the technically correct {@code <C extends Comparable<? super C>>}, to 101 * support legacy types from before Java 5. 102 */ 103 @GwtCompatible(serializable = true) 104 @SuppressWarnings("unchecked") // TODO(kevinb): right way to explain this?? natural()105 public static <C extends Comparable> Ordering<C> natural() { 106 return (Ordering<C>) NaturalOrdering.INSTANCE; 107 } 108 109 // Static factories 110 111 /** 112 * Returns an ordering based on an <i>existing</i> comparator instance. Note 113 * that it is unnecessary to create a <i>new</i> anonymous inner class 114 * implementing {@code Comparator} just to pass it in here. Instead, simply 115 * subclass {@code Ordering} and implement its {@code compare} method 116 * directly. 117 * 118 * @param comparator the comparator that defines the order 119 * @return comparator itself if it is already an {@code Ordering}; otherwise 120 * an ordering that wraps that comparator 121 */ 122 @GwtCompatible(serializable = true) from(Comparator<T> comparator)123 public static <T> Ordering<T> from(Comparator<T> comparator) { 124 return (comparator instanceof Ordering) 125 ? (Ordering<T>) comparator 126 : new ComparatorOrdering<T>(comparator); 127 } 128 129 /** 130 * Simply returns its argument. 131 * 132 * @deprecated no need to use this 133 */ 134 @GwtCompatible(serializable = true) from(Ordering<T> ordering)135 @Deprecated public static <T> Ordering<T> from(Ordering<T> ordering) { 136 return checkNotNull(ordering); 137 } 138 139 /** 140 * Returns an ordering that compares objects according to the order in 141 * which they appear in the given list. Only objects present in the list 142 * (according to {@link Object#equals}) may be compared. This comparator 143 * imposes a "partial ordering" over the type {@code T}. Subsequent changes 144 * to the {@code valuesInOrder} list will have no effect on the returned 145 * comparator. Null values in the list are not supported. 146 * 147 * <p>The returned comparator throws an {@link ClassCastException} when it 148 * receives an input parameter that isn't among the provided values. 149 * 150 * <p>The generated comparator is serializable if all the provided values are 151 * serializable. 152 * 153 * @param valuesInOrder the values that the returned comparator will be able 154 * to compare, in the order the comparator should induce 155 * @return the comparator described above 156 * @throws NullPointerException if any of the provided values is null 157 * @throws IllegalArgumentException if {@code valuesInOrder} contains any 158 * duplicate values (according to {@link Object#equals}) 159 */ 160 @GwtCompatible(serializable = true) explicit(List<T> valuesInOrder)161 public static <T> Ordering<T> explicit(List<T> valuesInOrder) { 162 return new ExplicitOrdering<T>(valuesInOrder); 163 } 164 165 /** 166 * Returns an ordering that compares objects according to the order in 167 * which they are given to this method. Only objects present in the argument 168 * list (according to {@link Object#equals}) may be compared. This comparator 169 * imposes a "partial ordering" over the type {@code T}. Null values in the 170 * argument list are not supported. 171 * 172 * <p>The returned comparator throws a {@link ClassCastException} when it 173 * receives an input parameter that isn't among the provided values. 174 * 175 * <p>The generated comparator is serializable if all the provided values are 176 * serializable. 177 * 178 * @param leastValue the value which the returned comparator should consider 179 * the "least" of all values 180 * @param remainingValuesInOrder the rest of the values that the returned 181 * comparator will be able to compare, in the order the comparator should 182 * follow 183 * @return the comparator described above 184 * @throws NullPointerException if any of the provided values is null 185 * @throws IllegalArgumentException if any duplicate values (according to 186 * {@link Object#equals(Object)}) are present among the method arguments 187 */ 188 @GwtCompatible(serializable = true) explicit( T leastValue, T... remainingValuesInOrder)189 public static <T> Ordering<T> explicit( 190 T leastValue, T... remainingValuesInOrder) { 191 return explicit(Lists.asList(leastValue, remainingValuesInOrder)); 192 } 193 194 // Ordering<Object> singletons 195 196 /** 197 * Returns an ordering which treats all values as equal, indicating "no 198 * ordering." Passing this ordering to any <i>stable</i> sort algorithm 199 * results in no change to the order of elements. Note especially that {@link 200 * #sortedCopy} and {@link #immutableSortedCopy} are stable, and in the 201 * returned instance these are implemented by simply copying the source list. 202 * 203 * <p>Example: <pre> {@code 204 * 205 * Ordering.allEqual().nullsLast().sortedCopy( 206 * asList(t, null, e, s, null, t, null))}</pre> 207 * 208 * <p>Assuming {@code t}, {@code e} and {@code s} are non-null, this returns 209 * {@code [t, e, s, t, null, null, null]} regardlesss of the true comparison 210 * order of those three values (which might not even implement {@link 211 * Comparable} at all). 212 * 213 * <p><b>Warning:</b> by definition, this comparator is not <i>consistent with 214 * equals</i> (as defined {@linkplain Comparator here}). Avoid its use in 215 * APIs, such as {@link TreeSet#TreeSet(Comparator)}, where such consistency 216 * is expected. 217 * 218 * <p>The returned comparator is serializable. 219 */ 220 @GwtCompatible(serializable = true) 221 @SuppressWarnings("unchecked") allEqual()222 public static Ordering<Object> allEqual() { 223 return AllEqualOrdering.INSTANCE; 224 } 225 226 /** 227 * Returns an ordering that compares objects by the natural ordering of their 228 * string representations as returned by {@code toString()}. It does not 229 * support null values. 230 * 231 * <p>The comparator is serializable. 232 */ 233 @GwtCompatible(serializable = true) usingToString()234 public static Ordering<Object> usingToString() { 235 return UsingToStringOrdering.INSTANCE; 236 } 237 238 /** 239 * Returns an arbitrary ordering over all objects, for which {@code compare(a, 240 * b) == 0} implies {@code a == b} (identity equality). There is no meaning 241 * whatsoever to the order imposed, but it is constant for the life of the VM. 242 * 243 * <p>Because the ordering is identity-based, it is not "consistent with 244 * {@link Object#equals(Object)}" as defined by {@link Comparator}. Use 245 * caution when building a {@link SortedSet} or {@link SortedMap} from it, as 246 * the resulting collection will not behave exactly according to spec. 247 * 248 * <p>This ordering is not serializable, as its implementation relies on 249 * {@link System#identityHashCode(Object)}, so its behavior cannot be 250 * preserved across serialization. 251 * 252 * @since 2.0 253 */ arbitrary()254 public static Ordering<Object> arbitrary() { 255 return ArbitraryOrderingHolder.ARBITRARY_ORDERING; 256 } 257 258 private static class ArbitraryOrderingHolder { 259 static final Ordering<Object> ARBITRARY_ORDERING = new ArbitraryOrdering(); 260 } 261 262 @VisibleForTesting static class ArbitraryOrdering extends Ordering<Object> { 263 @SuppressWarnings("deprecation") // TODO(kevinb): ? 264 private Map<Object, Integer> uids = 265 Platform.tryWeakKeys(new MapMaker()).makeComputingMap( 266 new Function<Object, Integer>() { 267 final AtomicInteger counter = new AtomicInteger(0); 268 @Override 269 public Integer apply(Object from) { 270 return counter.getAndIncrement(); 271 } 272 }); 273 compare(Object left, Object right)274 @Override public int compare(Object left, Object right) { 275 if (left == right) { 276 return 0; 277 } else if (left == null) { 278 return -1; 279 } else if (right == null) { 280 return 1; 281 } 282 int leftCode = identityHashCode(left); 283 int rightCode = identityHashCode(right); 284 if (leftCode != rightCode) { 285 return leftCode < rightCode ? -1 : 1; 286 } 287 288 // identityHashCode collision (rare, but not as rare as you'd think) 289 int result = uids.get(left).compareTo(uids.get(right)); 290 if (result == 0) { 291 throw new AssertionError(); // extremely, extremely unlikely. 292 } 293 return result; 294 } 295 toString()296 @Override public String toString() { 297 return "Ordering.arbitrary()"; 298 } 299 300 /* 301 * We need to be able to mock identityHashCode() calls for tests, because it 302 * can take 1-10 seconds to find colliding objects. Mocking frameworks that 303 * can do magic to mock static method calls still can't do so for a system 304 * class, so we need the indirection. In production, Hotspot should still 305 * recognize that the call is 1-morphic and should still be willing to 306 * inline it if necessary. 307 */ identityHashCode(Object object)308 int identityHashCode(Object object) { 309 return System.identityHashCode(object); 310 } 311 } 312 313 // Constructor 314 315 /** 316 * Constructs a new instance of this class (only invokable by the subclass 317 * constructor, typically implicit). 318 */ Ordering()319 protected Ordering() {} 320 321 // Instance-based factories (and any static equivalents) 322 323 /** 324 * Returns the reverse of this ordering; the {@code Ordering} equivalent to 325 * {@link Collections#reverseOrder(Comparator)}. 326 */ 327 // type parameter <S> lets us avoid the extra <String> in statements like: 328 // Ordering<String> o = Ordering.<String>natural().reverse(); 329 @GwtCompatible(serializable = true) reverse()330 public <S extends T> Ordering<S> reverse() { 331 return new ReverseOrdering<S>(this); 332 } 333 334 /** 335 * Returns an ordering that treats {@code null} as less than all other values 336 * and uses {@code this} to compare non-null values. 337 */ 338 // type parameter <S> lets us avoid the extra <String> in statements like: 339 // Ordering<String> o = Ordering.<String>natural().nullsFirst(); 340 @GwtCompatible(serializable = true) nullsFirst()341 public <S extends T> Ordering<S> nullsFirst() { 342 return new NullsFirstOrdering<S>(this); 343 } 344 345 /** 346 * Returns an ordering that treats {@code null} as greater than all other 347 * values and uses this ordering to compare non-null values. 348 */ 349 // type parameter <S> lets us avoid the extra <String> in statements like: 350 // Ordering<String> o = Ordering.<String>natural().nullsLast(); 351 @GwtCompatible(serializable = true) nullsLast()352 public <S extends T> Ordering<S> nullsLast() { 353 return new NullsLastOrdering<S>(this); 354 } 355 356 /** 357 * Returns a new ordering on {@code F} which orders elements by first applying 358 * a function to them, then comparing those results using {@code this}. For 359 * example, to compare objects by their string forms, in a case-insensitive 360 * manner, use: <pre> {@code 361 * 362 * Ordering.from(String.CASE_INSENSITIVE_ORDER) 363 * .onResultOf(Functions.toStringFunction())}</pre> 364 */ 365 @GwtCompatible(serializable = true) onResultOf(Function<F, ? extends T> function)366 public <F> Ordering<F> onResultOf(Function<F, ? extends T> function) { 367 return new ByFunctionOrdering<F, T>(function, this); 368 } 369 onKeys()370 <T2 extends T> Ordering<Map.Entry<T2, ?>> onKeys() { 371 return onResultOf(Maps.<T2>keyFunction()); 372 } 373 374 /** 375 * Returns an ordering which first uses the ordering {@code this}, but which 376 * in the event of a "tie", then delegates to {@code secondaryComparator}. 377 * For example, to sort a bug list first by status and second by priority, you 378 * might use {@code byStatus.compound(byPriority)}. For a compound ordering 379 * with three or more components, simply chain multiple calls to this method. 380 * 381 * <p>An ordering produced by this method, or a chain of calls to this method, 382 * is equivalent to one created using {@link Ordering#compound(Iterable)} on 383 * the same component comparators. 384 */ 385 @GwtCompatible(serializable = true) compound( Comparator<? super U> secondaryComparator)386 public <U extends T> Ordering<U> compound( 387 Comparator<? super U> secondaryComparator) { 388 return new CompoundOrdering<U>(this, checkNotNull(secondaryComparator)); 389 } 390 391 /** 392 * Returns an ordering which tries each given comparator in order until a 393 * non-zero result is found, returning that result, and returning zero only if 394 * all comparators return zero. The returned ordering is based on the state of 395 * the {@code comparators} iterable at the time it was provided to this 396 * method. 397 * 398 * <p>The returned ordering is equivalent to that produced using {@code 399 * Ordering.from(comp1).compound(comp2).compound(comp3) . . .}. 400 * 401 * <p><b>Warning:</b> Supplying an argument with undefined iteration order, 402 * such as a {@link HashSet}, will produce non-deterministic results. 403 * 404 * @param comparators the comparators to try in order 405 */ 406 @GwtCompatible(serializable = true) compound( Iterable<? extends Comparator<? super T>> comparators)407 public static <T> Ordering<T> compound( 408 Iterable<? extends Comparator<? super T>> comparators) { 409 return new CompoundOrdering<T>(comparators); 410 } 411 412 /** 413 * Returns a new ordering which sorts iterables by comparing corresponding 414 * elements pairwise until a nonzero result is found; imposes "dictionary 415 * order". If the end of one iterable is reached, but not the other, the 416 * shorter iterable is considered to be less than the longer one. For example, 417 * a lexicographical natural ordering over integers considers {@code 418 * [] < [1] < [1, 1] < [1, 2] < [2]}. 419 * 420 * <p>Note that {@code ordering.lexicographical().reverse()} is not 421 * equivalent to {@code ordering.reverse().lexicographical()} (consider how 422 * each would order {@code [1]} and {@code [1, 1]}). 423 * 424 * @since 2.0 425 */ 426 @GwtCompatible(serializable = true) 427 // type parameter <S> lets us avoid the extra <String> in statements like: 428 // Ordering<Iterable<String>> o = 429 // Ordering.<String>natural().lexicographical(); lexicographical()430 public <S extends T> Ordering<Iterable<S>> lexicographical() { 431 /* 432 * Note that technically the returned ordering should be capable of 433 * handling not just {@code Iterable<S>} instances, but also any {@code 434 * Iterable<? extends S>}. However, the need for this comes up so rarely 435 * that it doesn't justify making everyone else deal with the very ugly 436 * wildcard. 437 */ 438 return new LexicographicalOrdering<S>(this); 439 } 440 441 // Regular instance methods 442 443 // Override to add @Nullable compare(@ullable T left, @Nullable T right)444 @Override public abstract int compare(@Nullable T left, @Nullable T right); 445 446 /** 447 * Returns the least of the specified values according to this ordering. If 448 * there are multiple least values, the first of those is returned. The 449 * iterator will be left exhausted: its {@code hasNext()} method will return 450 * {@code false}. 451 * 452 * @param iterator the iterator whose minimum element is to be determined 453 * @throws NoSuchElementException if {@code iterator} is empty 454 * @throws ClassCastException if the parameters are not <i>mutually 455 * comparable</i> under this ordering. 456 * 457 * @since 11.0 458 */ min(Iterator<E> iterator)459 public <E extends T> E min(Iterator<E> iterator) { 460 // let this throw NoSuchElementException as necessary 461 E minSoFar = iterator.next(); 462 463 while (iterator.hasNext()) { 464 minSoFar = min(minSoFar, iterator.next()); 465 } 466 467 return minSoFar; 468 } 469 470 /** 471 * Returns the least of the specified values according to this ordering. If 472 * there are multiple least values, the first of those is returned. 473 * 474 * @param iterable the iterable whose minimum element is to be determined 475 * @throws NoSuchElementException if {@code iterable} is empty 476 * @throws ClassCastException if the parameters are not <i>mutually 477 * comparable</i> under this ordering. 478 */ min(Iterable<E> iterable)479 public <E extends T> E min(Iterable<E> iterable) { 480 return min(iterable.iterator()); 481 } 482 483 /** 484 * Returns the lesser of the two values according to this ordering. If the 485 * values compare as 0, the first is returned. 486 * 487 * <p><b>Implementation note:</b> this method is invoked by the default 488 * implementations of the other {@code min} overloads, so overriding it will 489 * affect their behavior. 490 * 491 * @param a value to compare, returned if less than or equal to b. 492 * @param b value to compare. 493 * @throws ClassCastException if the parameters are not <i>mutually 494 * comparable</i> under this ordering. 495 */ min(@ullable E a, @Nullable E b)496 public <E extends T> E min(@Nullable E a, @Nullable E b) { 497 return (compare(a, b) <= 0) ? a : b; 498 } 499 500 /** 501 * Returns the least of the specified values according to this ordering. If 502 * there are multiple least values, the first of those is returned. 503 * 504 * @param a value to compare, returned if less than or equal to the rest. 505 * @param b value to compare 506 * @param c value to compare 507 * @param rest values to compare 508 * @throws ClassCastException if the parameters are not <i>mutually 509 * comparable</i> under this ordering. 510 */ min( @ullable E a, @Nullable E b, @Nullable E c, E... rest)511 public <E extends T> E min( 512 @Nullable E a, @Nullable E b, @Nullable E c, E... rest) { 513 E minSoFar = min(min(a, b), c); 514 515 for (E r : rest) { 516 minSoFar = min(minSoFar, r); 517 } 518 519 return minSoFar; 520 } 521 522 /** 523 * Returns the greatest of the specified values according to this ordering. If 524 * there are multiple greatest values, the first of those is returned. The 525 * iterator will be left exhausted: its {@code hasNext()} method will return 526 * {@code false}. 527 * 528 * @param iterator the iterator whose maximum element is to be determined 529 * @throws NoSuchElementException if {@code iterator} is empty 530 * @throws ClassCastException if the parameters are not <i>mutually 531 * comparable</i> under this ordering. 532 * 533 * @since 11.0 534 */ max(Iterator<E> iterator)535 public <E extends T> E max(Iterator<E> iterator) { 536 // let this throw NoSuchElementException as necessary 537 E maxSoFar = iterator.next(); 538 539 while (iterator.hasNext()) { 540 maxSoFar = max(maxSoFar, iterator.next()); 541 } 542 543 return maxSoFar; 544 } 545 546 /** 547 * Returns the greatest of the specified values according to this ordering. If 548 * there are multiple greatest values, the first of those is returned. 549 * 550 * @param iterable the iterable whose maximum element is to be determined 551 * @throws NoSuchElementException if {@code iterable} is empty 552 * @throws ClassCastException if the parameters are not <i>mutually 553 * comparable</i> under this ordering. 554 */ max(Iterable<E> iterable)555 public <E extends T> E max(Iterable<E> iterable) { 556 return max(iterable.iterator()); 557 } 558 559 /** 560 * Returns the greater of the two values according to this ordering. If the 561 * values compare as 0, the first is returned. 562 * 563 * <p><b>Implementation note:</b> this method is invoked by the default 564 * implementations of the other {@code max} overloads, so overriding it will 565 * affect their behavior. 566 * 567 * @param a value to compare, returned if greater than or equal to b. 568 * @param b value to compare. 569 * @throws ClassCastException if the parameters are not <i>mutually 570 * comparable</i> under this ordering. 571 */ max(@ullable E a, @Nullable E b)572 public <E extends T> E max(@Nullable E a, @Nullable E b) { 573 return (compare(a, b) >= 0) ? a : b; 574 } 575 576 /** 577 * Returns the greatest of the specified values according to this ordering. If 578 * there are multiple greatest values, the first of those is returned. 579 * 580 * @param a value to compare, returned if greater than or equal to the rest. 581 * @param b value to compare 582 * @param c value to compare 583 * @param rest values to compare 584 * @throws ClassCastException if the parameters are not <i>mutually 585 * comparable</i> under this ordering. 586 */ max( @ullable E a, @Nullable E b, @Nullable E c, E... rest)587 public <E extends T> E max( 588 @Nullable E a, @Nullable E b, @Nullable E c, E... rest) { 589 E maxSoFar = max(max(a, b), c); 590 591 for (E r : rest) { 592 maxSoFar = max(maxSoFar, r); 593 } 594 595 return maxSoFar; 596 } 597 598 /** 599 * Returns the {@code k} least elements of the given iterable according to 600 * this ordering, in order from least to greatest. If there are fewer than 601 * {@code k} elements present, all will be included. 602 * 603 * <p>The implementation does not necessarily use a <i>stable</i> sorting 604 * algorithm; when multiple elements are equivalent, it is undefined which 605 * will come first. 606 * 607 * @return an immutable {@code RandomAccess} list of the {@code k} least 608 * elements in ascending order 609 * @throws IllegalArgumentException if {@code k} is negative 610 * @since 8.0 611 */ leastOf(Iterable<E> iterable, int k)612 public <E extends T> List<E> leastOf(Iterable<E> iterable, int k) { 613 if (iterable instanceof Collection) { 614 Collection<E> collection = (Collection<E>) iterable; 615 if (collection.size() <= 2L * k) { 616 // In this case, just dumping the collection to an array and sorting is 617 // faster than using the implementation for Iterator, which is 618 // specialized for k much smaller than n. 619 620 @SuppressWarnings("unchecked") // c only contains E's and doesn't escape 621 E[] array = (E[]) collection.toArray(); 622 Arrays.sort(array, this); 623 if (array.length > k) { 624 array = ObjectArrays.arraysCopyOf(array, k); 625 } 626 return Collections.unmodifiableList(Arrays.asList(array)); 627 } 628 } 629 return leastOf(iterable.iterator(), k); 630 } 631 632 /** 633 * Returns the {@code k} least elements from the given iterator according to 634 * this ordering, in order from least to greatest. If there are fewer than 635 * {@code k} elements present, all will be included. 636 * 637 * <p>The implementation does not necessarily use a <i>stable</i> sorting 638 * algorithm; when multiple elements are equivalent, it is undefined which 639 * will come first. 640 * 641 * @return an immutable {@code RandomAccess} list of the {@code k} least 642 * elements in ascending order 643 * @throws IllegalArgumentException if {@code k} is negative 644 * @since 14.0 645 */ leastOf(Iterator<E> elements, int k)646 public <E extends T> List<E> leastOf(Iterator<E> elements, int k) { 647 checkNotNull(elements); 648 checkNonnegative(k, "k"); 649 650 if (k == 0 || !elements.hasNext()) { 651 return ImmutableList.of(); 652 } else if (k >= Integer.MAX_VALUE / 2) { 653 // k is really large; just do a straightforward sorted-copy-and-sublist 654 ArrayList<E> list = Lists.newArrayList(elements); 655 Collections.sort(list, this); 656 if (list.size() > k) { 657 list.subList(k, list.size()).clear(); 658 } 659 list.trimToSize(); 660 return Collections.unmodifiableList(list); 661 } 662 663 /* 664 * Our goal is an O(n) algorithm using only one pass and O(k) additional 665 * memory. 666 * 667 * We use the following algorithm: maintain a buffer of size 2*k. Every time 668 * the buffer gets full, find the median and partition around it, keeping 669 * only the lowest k elements. This requires n/k find-median-and-partition 670 * steps, each of which take O(k) time with a traditional quickselect. 671 * 672 * After sorting the output, the whole algorithm is O(n + k log k). It 673 * degrades gracefully for worst-case input (descending order), performs 674 * competitively or wins outright for randomly ordered input, and doesn't 675 * require the whole collection to fit into memory. 676 */ 677 int bufferCap = k * 2; 678 @SuppressWarnings("unchecked") // we'll only put E's in 679 E[] buffer = (E[]) new Object[bufferCap]; 680 E threshold = elements.next(); 681 buffer[0] = threshold; 682 int bufferSize = 1; 683 // threshold is the kth smallest element seen so far. Once bufferSize >= k, 684 // anything larger than threshold can be ignored immediately. 685 686 while (bufferSize < k && elements.hasNext()) { 687 E e = elements.next(); 688 buffer[bufferSize++] = e; 689 threshold = max(threshold, e); 690 } 691 692 while (elements.hasNext()) { 693 E e = elements.next(); 694 if (compare(e, threshold) >= 0) { 695 continue; 696 } 697 698 buffer[bufferSize++] = e; 699 if (bufferSize == bufferCap) { 700 // We apply the quickselect algorithm to partition about the median, 701 // and then ignore the last k elements. 702 int left = 0; 703 int right = bufferCap - 1; 704 705 int minThresholdPosition = 0; 706 // The leftmost position at which the greatest of the k lower elements 707 // -- the new value of threshold -- might be found. 708 709 while (left < right) { 710 int pivotIndex = (left + right + 1) >>> 1; 711 int pivotNewIndex = partition(buffer, left, right, pivotIndex); 712 if (pivotNewIndex > k) { 713 right = pivotNewIndex - 1; 714 } else if (pivotNewIndex < k) { 715 left = Math.max(pivotNewIndex, left + 1); 716 minThresholdPosition = pivotNewIndex; 717 } else { 718 break; 719 } 720 } 721 bufferSize = k; 722 723 threshold = buffer[minThresholdPosition]; 724 for (int i = minThresholdPosition + 1; i < bufferSize; i++) { 725 threshold = max(threshold, buffer[i]); 726 } 727 } 728 } 729 730 Arrays.sort(buffer, 0, bufferSize, this); 731 732 bufferSize = Math.min(bufferSize, k); 733 return Collections.unmodifiableList( 734 Arrays.asList(ObjectArrays.arraysCopyOf(buffer, bufferSize))); 735 // We can't use ImmutableList; we have to be null-friendly! 736 } 737 partition( E[] values, int left, int right, int pivotIndex)738 private <E extends T> int partition( 739 E[] values, int left, int right, int pivotIndex) { 740 E pivotValue = values[pivotIndex]; 741 742 values[pivotIndex] = values[right]; 743 values[right] = pivotValue; 744 745 int storeIndex = left; 746 for (int i = left; i < right; i++) { 747 if (compare(values[i], pivotValue) < 0) { 748 ObjectArrays.swap(values, storeIndex, i); 749 storeIndex++; 750 } 751 } 752 ObjectArrays.swap(values, right, storeIndex); 753 return storeIndex; 754 } 755 756 /** 757 * Returns the {@code k} greatest elements of the given iterable according to 758 * this ordering, in order from greatest to least. If there are fewer than 759 * {@code k} elements present, all will be included. 760 * 761 * <p>The implementation does not necessarily use a <i>stable</i> sorting 762 * algorithm; when multiple elements are equivalent, it is undefined which 763 * will come first. 764 * 765 * @return an immutable {@code RandomAccess} list of the {@code k} greatest 766 * elements in <i>descending order</i> 767 * @throws IllegalArgumentException if {@code k} is negative 768 * @since 8.0 769 */ greatestOf(Iterable<E> iterable, int k)770 public <E extends T> List<E> greatestOf(Iterable<E> iterable, int k) { 771 // TODO(kevinb): see if delegation is hurting performance noticeably 772 // TODO(kevinb): if we change this implementation, add full unit tests. 773 return reverse().leastOf(iterable, k); 774 } 775 776 /** 777 * Returns the {@code k} greatest elements from the given iterator according to 778 * this ordering, in order from greatest to least. If there are fewer than 779 * {@code k} elements present, all will be included. 780 * 781 * <p>The implementation does not necessarily use a <i>stable</i> sorting 782 * algorithm; when multiple elements are equivalent, it is undefined which 783 * will come first. 784 * 785 * @return an immutable {@code RandomAccess} list of the {@code k} greatest 786 * elements in <i>descending order</i> 787 * @throws IllegalArgumentException if {@code k} is negative 788 * @since 14.0 789 */ greatestOf(Iterator<E> iterator, int k)790 public <E extends T> List<E> greatestOf(Iterator<E> iterator, int k) { 791 return reverse().leastOf(iterator, k); 792 } 793 794 /** 795 * Returns a <b>mutable</b> list containing {@code elements} sorted by this 796 * ordering; use this only when the resulting list may need further 797 * modification, or may contain {@code null}. The input is not modified. The 798 * returned list is serializable and has random access. 799 * 800 * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard 801 * elements that are duplicates according to the comparator. The sort 802 * performed is <i>stable</i>, meaning that such elements will appear in the 803 * returned list in the same order they appeared in {@code elements}. 804 * 805 * <p><b>Performance note:</b> According to our 806 * benchmarking 807 * on Open JDK 7, {@link #immutableSortedCopy} generally performs better (in 808 * both time and space) than this method, and this method in turn generally 809 * performs better than copying the list and calling {@link 810 * Collections#sort(List)}. 811 */ sortedCopy(Iterable<E> elements)812 public <E extends T> List<E> sortedCopy(Iterable<E> elements) { 813 @SuppressWarnings("unchecked") // does not escape, and contains only E's 814 E[] array = (E[]) Iterables.toArray(elements); 815 Arrays.sort(array, this); 816 return Lists.newArrayList(Arrays.asList(array)); 817 } 818 819 /** 820 * Returns an <b>immutable</b> list containing {@code elements} sorted by this 821 * ordering. The input is not modified. 822 * 823 * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard 824 * elements that are duplicates according to the comparator. The sort 825 * performed is <i>stable</i>, meaning that such elements will appear in the 826 * returned list in the same order they appeared in {@code elements}. 827 * 828 * <p><b>Performance note:</b> According to our 829 * benchmarking 830 * on Open JDK 7, this method is the most efficient way to make a sorted copy 831 * of a collection. 832 * 833 * @throws NullPointerException if any of {@code elements} (or {@code 834 * elements} itself) is null 835 * @since 3.0 836 */ immutableSortedCopy( Iterable<E> elements)837 public <E extends T> ImmutableList<E> immutableSortedCopy( 838 Iterable<E> elements) { 839 @SuppressWarnings("unchecked") // we'll only ever have E's in here 840 E[] array = (E[]) Iterables.toArray(elements); 841 for (E e : array) { 842 checkNotNull(e); 843 } 844 Arrays.sort(array, this); 845 return ImmutableList.asImmutableList(array); 846 } 847 848 /** 849 * Returns {@code true} if each element in {@code iterable} after the first is 850 * greater than or equal to the element that preceded it, according to this 851 * ordering. Note that this is always true when the iterable has fewer than 852 * two elements. 853 */ isOrdered(Iterable<? extends T> iterable)854 public boolean isOrdered(Iterable<? extends T> iterable) { 855 Iterator<? extends T> it = iterable.iterator(); 856 if (it.hasNext()) { 857 T prev = it.next(); 858 while (it.hasNext()) { 859 T next = it.next(); 860 if (compare(prev, next) > 0) { 861 return false; 862 } 863 prev = next; 864 } 865 } 866 return true; 867 } 868 869 /** 870 * Returns {@code true} if each element in {@code iterable} after the first is 871 * <i>strictly</i> greater than the element that preceded it, according to 872 * this ordering. Note that this is always true when the iterable has fewer 873 * than two elements. 874 */ isStrictlyOrdered(Iterable<? extends T> iterable)875 public boolean isStrictlyOrdered(Iterable<? extends T> iterable) { 876 Iterator<? extends T> it = iterable.iterator(); 877 if (it.hasNext()) { 878 T prev = it.next(); 879 while (it.hasNext()) { 880 T next = it.next(); 881 if (compare(prev, next) >= 0) { 882 return false; 883 } 884 prev = next; 885 } 886 } 887 return true; 888 } 889 890 /** 891 * {@link Collections#binarySearch(List, Object, Comparator) Searches} 892 * {@code sortedList} for {@code key} using the binary search algorithm. The 893 * list must be sorted using this ordering. 894 * 895 * @param sortedList the list to be searched 896 * @param key the key to be searched for 897 */ binarySearch(List<? extends T> sortedList, @Nullable T key)898 public int binarySearch(List<? extends T> sortedList, @Nullable T key) { 899 return Collections.binarySearch(sortedList, key, this); 900 } 901 902 /** 903 * Exception thrown by a {@link Ordering#explicit(List)} or {@link 904 * Ordering#explicit(Object, Object[])} comparator when comparing a value 905 * outside the set of values it can compare. Extending {@link 906 * ClassCastException} may seem odd, but it is required. 907 */ 908 // TODO(kevinb): make this public, document it right 909 @VisibleForTesting 910 static class IncomparableValueException extends ClassCastException { 911 final Object value; 912 IncomparableValueException(Object value)913 IncomparableValueException(Object value) { 914 super("Cannot compare value: " + value); 915 this.value = value; 916 } 917 918 private static final long serialVersionUID = 0; 919 } 920 921 // Never make these public 922 static final int LEFT_IS_GREATER = 1; 923 static final int RIGHT_IS_GREATER = -1; 924 } 925