1 /* 2 * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package javany.util; 27 28 import java.io.Serializable; 29 import java.util.Objects; 30 31 import javany.util.function.Function; 32 33 /** 34 * A comparison function, which imposes a <i>total ordering</i> on some 35 * collection of objects. Comparators can be passed to a sort method (such 36 * as {@link Collections#sort(List,Comparator) Collections.sort} or {@link 37 * Arrays#sort(Object[],Comparator) Arrays.sort}) to allow precise control 38 * over the sort order. Comparators can also be used to control the order of 39 * certain data structures (such as {@link SortedSet sorted sets} or {@link 40 * SortedMap sorted maps}), or to provide an ordering for collections of 41 * objects that don't have a {@link Comparable natural ordering}.<p> 42 * 43 * The ordering imposed by a comparator <tt>c</tt> on a set of elements 44 * <tt>S</tt> is said to be <i>consistent with equals</i> if and only if 45 * <tt>c.compare(e1, e2)==0</tt> has the same boolean value as 46 * <tt>e1.equals(e2)</tt> for every <tt>e1</tt> and <tt>e2</tt> in 47 * <tt>S</tt>.<p> 48 * 49 * Caution should be exercised when using a comparator capable of imposing an 50 * ordering inconsistent with equals to order a sorted set (or sorted map). 51 * Suppose a sorted set (or sorted map) with an explicit comparator <tt>c</tt> 52 * is used with elements (or keys) drawn from a set <tt>S</tt>. If the 53 * ordering imposed by <tt>c</tt> on <tt>S</tt> is inconsistent with equals, 54 * the sorted set (or sorted map) will behave "strangely." In particular the 55 * sorted set (or sorted map) will violate the general contract for set (or 56 * map), which is defined in terms of <tt>equals</tt>.<p> 57 * 58 * For example, suppose one adds two elements {@code a} and {@code b} such that 59 * {@code (a.equals(b) && c.compare(a, b) != 0)} 60 * to an empty {@code TreeSet} with comparator {@code c}. 61 * The second {@code add} operation will return 62 * true (and the size of the tree set will increase) because {@code a} and 63 * {@code b} are not equivalent from the tree set's perspective, even though 64 * this is contrary to the specification of the 65 * {@link Set#add Set.add} method.<p> 66 * 67 * Note: It is generally a good idea for comparators to also implement 68 * <tt>java.io.Serializable</tt>, as they may be used as ordering methods in 69 * serializable data structures (like {@link TreeSet}, {@link TreeMap}). In 70 * order for the data structure to serialize successfully, the comparator (if 71 * provided) must implement <tt>Serializable</tt>.<p> 72 * 73 * For the mathematically inclined, the <i>relation</i> that defines the 74 * <i>imposed ordering</i> that a given comparator <tt>c</tt> imposes on a 75 * given set of objects <tt>S</tt> is:<pre> 76 * {(x, y) such that c.compare(x, y) <= 0}. 77 * </pre> The <i>quotient</i> for this total order is:<pre> 78 * {(x, y) such that c.compare(x, y) == 0}. 79 * </pre> 80 * 81 * It follows immediately from the contract for <tt>compare</tt> that the 82 * quotient is an <i>equivalence relation</i> on <tt>S</tt>, and that the 83 * imposed ordering is a <i>total order</i> on <tt>S</tt>. When we say that 84 * the ordering imposed by <tt>c</tt> on <tt>S</tt> is <i>consistent with 85 * equals</i>, we mean that the quotient for the ordering is the equivalence 86 * relation defined by the objects' {@link Object#equals(Object) 87 * equals(Object)} method(s):<pre> 88 * {(x, y) such that x.equals(y)}. </pre> 89 * 90 * <p>Unlike {@code Comparable}, a comparator may optionally permit 91 * comparison of null arguments, while maintaining the requirements for 92 * an equivalence relation. 93 * 94 * <p>This interface is a member of the 95 * <a href="{@docRoot}/../technotes/guides/collections/index.html"> 96 * Java Collections Framework</a>. 97 * 98 * @param <T> the type of objects that may be compared by this comparator 99 * 100 * @author Josh Bloch 101 * @author Neal Gafter 102 * @see Comparable 103 * @see java.io.Serializable 104 * @since 1.2 105 */ 106 @FunctionalInterface 107 public interface Comparator<any T> { 108 /** 109 * Compares its two arguments for order. Returns a negative integer, 110 * zero, or a positive integer as the first argument is less than, equal 111 * to, or greater than the second.<p> 112 * 113 * In the foregoing description, the notation 114 * <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical 115 * <i>signum</i> function, which is defined to return one of <tt>-1</tt>, 116 * <tt>0</tt>, or <tt>1</tt> according to whether the value of 117 * <i>expression</i> is negative, zero or positive.<p> 118 * 119 * The implementor must ensure that <tt>sgn(compare(x, y)) == 120 * -sgn(compare(y, x))</tt> for all <tt>x</tt> and <tt>y</tt>. (This 121 * implies that <tt>compare(x, y)</tt> must throw an exception if and only 122 * if <tt>compare(y, x)</tt> throws an exception.)<p> 123 * 124 * The implementor must also ensure that the relation is transitive: 125 * <tt>((compare(x, y)>0) && (compare(y, z)>0))</tt> implies 126 * <tt>compare(x, z)>0</tt>.<p> 127 * 128 * Finally, the implementor must ensure that <tt>compare(x, y)==0</tt> 129 * implies that <tt>sgn(compare(x, z))==sgn(compare(y, z))</tt> for all 130 * <tt>z</tt>.<p> 131 * 132 * It is generally the case, but <i>not</i> strictly required that 133 * <tt>(compare(x, y)==0) == (x.equals(y))</tt>. Generally speaking, 134 * any comparator that violates this condition should clearly indicate 135 * this fact. The recommended language is "Note: this comparator 136 * imposes orderings that are inconsistent with equals." 137 * 138 * @param o1 the first object to be compared. 139 * @param o2 the second object to be compared. 140 * @return a negative integer, zero, or a positive integer as the 141 * first argument is less than, equal to, or greater than the 142 * second. 143 * @throws NullPointerException if an argument is null and this 144 * comparator does not permit null arguments 145 * @throws ClassCastException if the arguments' types prevent them from 146 * being compared by this comparator. 147 */ 148 int compare(T o1, T o2); 149 150 /** 151 * Indicates whether some other object is "equal to" this 152 * comparator. This method must obey the general contract of 153 * {@link Object#equals(Object)}. Additionally, this method can return 154 * <tt>true</tt> <i>only</i> if the specified object is also a comparator 155 * and it imposes the same ordering as this comparator. Thus, 156 * <code>comp1.equals(comp2)</code> implies that <tt>sgn(comp1.compare(o1, 157 * o2))==sgn(comp2.compare(o1, o2))</tt> for every object reference 158 * <tt>o1</tt> and <tt>o2</tt>.<p> 159 * 160 * Note that it is <i>always</i> safe <i>not</i> to override 161 * <tt>Object.equals(Object)</tt>. However, overriding this method may, 162 * in some cases, improve performance by allowing programs to determine 163 * that two distinct comparators impose the same order. 164 * 165 * @param obj the reference object with which to compare. 166 * @return <code>true</code> only if the specified object is also 167 * a comparator and it imposes the same ordering as this 168 * comparator. 169 * @see Object#equals(Object) 170 * @see Object#hashCode() 171 */ 172 boolean equals(Object obj); 173 174 /** 175 * Returns a comparator that imposes the reverse ordering of this 176 * comparator. 177 * 178 * @return a comparator that imposes the reverse ordering of this 179 * comparator. 180 * @since 1.8 181 */ 182 default Comparator<T> reversed() { 183 return new Comparators.ReverseComparator<>(this); 184 } 185 186 /** 187 * Returns a lexicographic-order comparator with another comparator. 188 * If this {@code Comparator} considers two elements equal, i.e. 189 * {@code compare(a, b) == 0}, {@code other} is used to determine the order. 190 * 191 * <p>The returned comparator is serializable if the specified comparator 192 * is also serializable. 193 * 194 * @apiNote 195 * For example, to sort a collection of {@code String} based on the length 196 * and then case-insensitive natural ordering, the comparator can be 197 * composed using following code, 198 * 199 * <pre>{@code 200 * Comparator<String> cmp = Comparator.comparingInt(String::length) 201 * .thenComparing(String.CASE_INSENSITIVE_ORDER); 202 * }</pre> 203 * 204 * @param other the other comparator to be used when this comparator 205 * compares two objects that are equal. 206 * @return a lexicographic-order comparator composed of this and then the 207 * other comparator 208 * @throws NullPointerException if the argument is null. 209 * @since 1.8 210 */ 211 default Comparator<T> thenComparing(Comparator<? super T> other) { 212 Objects.requireNonNull(other); 213 return (Comparator<T> & Serializable) (c1, c2) -> { 214 int res = compare(c1, c2); 215 return (res != 0) ? res : other.compare(c1, c2); 216 }; 217 } 218 219 /** 220 * Returns a lexicographic-order comparator with a function that 221 * extracts a key to be compared with the given {@code Comparator}. 222 * 223 * @implSpec This default implementation behaves as if {@code 224 * thenComparing(comparing(keyExtractor, cmp))}. 225 * 226 * @param <U> the type of the sort key 227 * @param keyExtractor the function used to extract the sort key 228 * @param keyComparator the {@code Comparator} used to compare the sort key 229 * @return a lexicographic-order comparator composed of this comparator 230 * and then comparing on the key extracted by the keyExtractor function 231 * @throws NullPointerException if either argument is null. 232 * @see #comparing(Function, Comparator) 233 * @see #thenComparing(Comparator) 234 * @since 1.8 235 */ 236 default <any U> Comparator<T> thenComparing( 237 Function<? super T, ? extends U> keyExtractor, 238 Comparator<? super U> keyComparator) 239 { 240 return thenComparing(comparing(keyExtractor, keyComparator)); 241 } 242 243 /** 244 * Returns a lexicographic-order comparator with a function that 245 * extracts a {@code Comparable} sort key. 246 * 247 * @implSpec This default implementation behaves as if {@code 248 * thenComparing(comparing(keyExtractor))}. 249 * 250 * @param <U> the type of the {@link Comparable} sort key 251 * @param keyExtractor the function used to extract the {@link 252 * Comparable} sort key 253 * @return a lexicographic-order comparator composed of this and then the 254 * {@link Comparable} sort key. 255 * @throws NullPointerException if the argument is null. 256 * @see #comparing(Function) 257 * @see #thenComparing(Comparator) 258 * @since 1.8 259 */ 260 default <U extends Comparable<? super U>> Comparator<T> thenComparing( 261 Function<? super T, ? extends U> keyExtractor) 262 { 263 return thenComparing(comparing(keyExtractor)); 264 } 265 266 /** 267 * Returns a lexicographic-order comparator with a function that 268 * extracts a {@code int} sort key. 269 * 270 * @implSpec This default implementation behaves as if {@code 271 * thenComparing(comparingInt(keyExtractor))}. 272 * 273 * @param keyExtractor the function used to extract the integer sort key 274 * @return a lexicographic-order comparator composed of this and then the 275 * {@code int} sort key 276 * @throws NullPointerException if the argument is null. 277 * @see #comparingInt(Function) 278 * @see #thenComparing(Comparator) 279 * @since 1.8 280 */ 281 default Comparator<T> thenComparingInt(Function<? super T, int> keyExtractor) { 282 return thenComparing(comparingInt(keyExtractor)); 283 } 284 285 /** 286 * Returns a lexicographic-order comparator with a function that 287 * extracts a {@code long} sort key. 288 * 289 * @implSpec This default implementation behaves as if {@code 290 * thenComparing(comparingLong(keyExtractor))}. 291 * 292 * @param keyExtractor the function used to extract the long sort key 293 * @return a lexicographic-order comparator composed of this and then the 294 * {@code long} sort key 295 * @throws NullPointerException if the argument is null. 296 * @see #comparingLong(Function) 297 * @see #thenComparing(Comparator) 298 * @since 1.8 299 */ 300 default Comparator<T> thenComparingLong(Function<? super T, long> keyExtractor) { 301 return thenComparing(comparingLong(keyExtractor)); 302 } 303 304 /** 305 * Returns a lexicographic-order comparator with a function that 306 * extracts a {@code double} sort key. 307 * 308 * @implSpec This default implementation behaves as if {@code 309 * thenComparing(comparingDouble(keyExtractor))}. 310 * 311 * @param keyExtractor the function used to extract the double sort key 312 * @return a lexicographic-order comparator composed of this and then the 313 * {@code double} sort key 314 * @throws NullPointerException if the argument is null. 315 * @see #comparingDouble(Function) 316 * @see #thenComparing(Comparator) 317 * @since 1.8 318 */ 319 default Comparator<T> thenComparingDouble(Function<? super T, double> keyExtractor) { 320 return thenComparing(comparingDouble(keyExtractor)); 321 } 322 323 /** 324 * Returns a comparator that imposes the reverse of the <em>natural 325 * ordering</em>. 326 * 327 * <p>The returned comparator is serializable and throws {@link 328 * NullPointerException} when comparing {@code null}. 329 * 330 * @param <T> the {@link Comparable} type of element to be compared 331 * @return a comparator that imposes the reverse of the <i>natural 332 * ordering</i> on {@code Comparable} objects. 333 * @see Comparable 334 * @since 1.8 335 */ 336 public static <any T> Comparator<T> reverseOrder() { 337 return Comparators.<T>naturalOrder().reversed(); 338 } 339 340 /** 341 * Returns a comparator that compares {@link Comparable} objects in natural 342 * order. 343 * 344 * <p>The returned comparator is serializable and throws {@link 345 * NullPointerException} when comparing {@code null}. 346 * 347 * @param <T> the {@link Comparable} type of element to be compared 348 * @return a comparator that imposes the <i>natural ordering</i> on {@code 349 * Comparable} objects. 350 * @see Comparable 351 * @since 1.8 352 */ 353 @SuppressWarnings("unchecked") 354 public static <any T> Comparator<T> naturalOrder() { 355 return Comparators.naturalOrder(); 356 } 357 358 /** 359 * Returns a null-friendly comparator that considers {@code null} to be 360 * less than non-null. When both are {@code null}, they are considered 361 * equal. If both are non-null, the specified {@code Comparator} is used 362 * to determine the order. If the specified comparator is {@code null}, 363 * then the returned comparator considers all non-null values to be equal. 364 * 365 * <p>The returned comparator is serializable if the specified comparator 366 * is serializable. 367 * 368 * @param <T> the type of the elements to be compared 369 * @param comparator a {@code Comparator} for comparing non-null values 370 * @return a comparator that considers {@code null} to be less than 371 * non-null, and compares non-null objects with the supplied 372 * {@code Comparator}. 373 * @since 1.8 374 */ 375 public static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator) { 376 return new Comparators.NullComparator<>(true, comparator); 377 } 378 379 /** 380 * Returns a null-friendly comparator that considers {@code null} to be 381 * greater than non-null. When both are {@code null}, they are considered 382 * equal. If both are non-null, the specified {@code Comparator} is used 383 * to determine the order. If the specified comparator is {@code null}, 384 * then the returned comparator considers all non-null values to be equal. 385 * 386 * <p>The returned comparator is serializable if the specified comparator 387 * is serializable. 388 * 389 * @param <T> the type of the elements to be compared 390 * @param comparator a {@code Comparator} for comparing non-null values 391 * @return a comparator that considers {@code null} to be greater than 392 * non-null, and compares non-null objects with the supplied 393 * {@code Comparator}. 394 * @since 1.8 395 */ 396 public static <T> Comparator<T> nullsLast(Comparator<? super T> comparator) { 397 return new Comparators.NullComparator<>(false, comparator); 398 } 399 400 /** 401 * Accepts a function that extracts a sort key from a type {@code T}, and 402 * returns a {@code Comparator<T>} that compares by that sort key using 403 * the specified {@link Comparator}. 404 * 405 * <p>The returned comparator is serializable if the specified function 406 * and comparator are both serializable. 407 * 408 * @apiNote 409 * For example, to obtain a {@code Comparator} that compares {@code 410 * Person} objects by their last name ignoring case differences, 411 * 412 * <pre>{@code 413 * Comparator<Person> cmp = Comparator.comparing( 414 * Person::getLastName, 415 * String.CASE_INSENSITIVE_ORDER); 416 * }</pre> 417 * 418 * @param <T> the type of element to be compared 419 * @param <U> the type of the sort key 420 * @param keyExtractor the function used to extract the sort key 421 * @param keyComparator the {@code Comparator} used to compare the sort key 422 * @return a comparator that compares by an extracted key using the 423 * specified {@code Comparator} 424 * @throws NullPointerException if either argument is null 425 * @since 1.8 426 */ 427 public static <any T, any U> Comparator<T> comparing( 428 Function<? super T, ? extends U> keyExtractor, 429 Comparator<? super U> keyComparator) 430 { 431 Objects.requireNonNull(keyExtractor); 432 Objects.requireNonNull(keyComparator); 433 return (Comparator<T> & Serializable) 434 (c1, c2) -> keyComparator.compare(keyExtractor.apply(c1), 435 keyExtractor.apply(c2)); 436 } 437 438 /** 439 * Accepts a function that extracts a {@link java.lang.Comparable 440 * Comparable} sort key from a type {@code T}, and returns a {@code 441 * Comparator<T>} that compares by that sort key. 442 * 443 * <p>The returned comparator is serializable if the specified function 444 * is also serializable. 445 * 446 * @apiNote 447 * For example, to obtain a {@code Comparator} that compares {@code 448 * Person} objects by their last name, 449 * 450 * <pre>{@code 451 * Comparator<Person> byLastName = Comparator.comparing(Person::getLastName); 452 * }</pre> 453 * 454 * @param <T> the type of element to be compared 455 * @param <U> the type of the {@code Comparable} sort key 456 * @param keyExtractor the function used to extract the {@link 457 * Comparable} sort key 458 * @return a comparator that compares by an extracted key 459 * @throws NullPointerException if the argument is null 460 * @since 1.8 461 */ 462 public static <any T, U extends Comparable<? super U>> Comparator<T> comparing( 463 Function<? super T, ? extends U> keyExtractor) 464 { 465 Objects.requireNonNull(keyExtractor); 466 return (Comparator<T> & Serializable) 467 (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2)); 468 } 469 470 /** 471 * Accepts a function that extracts an {@code int} sort key from a type 472 * {@code T}, and returns a {@code Comparator<T>} that compares by that 473 * sort key. 474 * 475 * <p>The returned comparator is serializable if the specified function 476 * is also serializable. 477 * 478 * @param <T> the type of element to be compared 479 * @param keyExtractor the function used to extract the integer sort key 480 * @return a comparator that compares by an extracted key 481 * @see #comparing(Function) 482 * @throws NullPointerException if the argument is null 483 * @since 1.8 484 */ 485 public static <any T> Comparator<T> comparingInt(Function<? super T, int> keyExtractor) { 486 Objects.requireNonNull(keyExtractor); 487 return (Comparator<T> & Serializable) 488 (c1, c2) -> Integer.compare(keyExtractor.apply(c1), keyExtractor.apply(c2)); 489 } 490 491 /** 492 * Accepts a function that extracts a {@code long} sort key from a type 493 * {@code T}, and returns a {@code Comparator<T>} that compares by that 494 * sort key. 495 * 496 * <p>The returned comparator is serializable if the specified function is 497 * also serializable. 498 * 499 * @param <T> the type of element to be compared 500 * @param keyExtractor the function used to extract the long sort key 501 * @return a comparator that compares by an extracted key 502 * @see #comparing(Function) 503 * @throws NullPointerException if the argument is null 504 * @since 1.8 505 */ 506 public static <any T> Comparator<T> comparingLong(Function<? super T, long> keyExtractor) { 507 Objects.requireNonNull(keyExtractor); 508 return (Comparator<T> & Serializable) 509 (c1, c2) -> Long.compare(keyExtractor.apply(c1), keyExtractor.apply(c2)); 510 } 511 512 /** 513 * Accepts a function that extracts a {@code double} sort key from a type 514 * {@code T}, and returns a {@code Comparator<T>} that compares by that 515 * sort key. 516 * 517 * <p>The returned comparator is serializable if the specified function 518 * is also serializable. 519 * 520 * @param <T> the type of element to be compared 521 * @param keyExtractor the function used to extract the double sort key 522 * @return a comparator that compares by an extracted key 523 * @see #comparing(Function) 524 * @throws NullPointerException if the argument is null 525 * @since 1.8 526 */ 527 public static <any T> Comparator<T> comparingDouble(Function<? super T, double> keyExtractor) { 528 Objects.requireNonNull(keyExtractor); 529 return (Comparator<T> & Serializable) 530 (c1, c2) -> Double.compare(keyExtractor.apply(c1), keyExtractor.apply(c2)); 531 } 532 }