1 /* 2 * Copyright (c) 1997, 2017, 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 java.util; 27 28 import java.io.Serializable; 29 import java.util.function.Function; 30 import java.util.function.ToIntFunction; 31 import java.util.function.ToLongFunction; 32 import java.util.function.ToDoubleFunction; 33 34 /** 35 * A comparison function, which imposes a <i>total ordering</i> on some 36 * collection of objects. Comparators can be passed to a sort method (such 37 * as {@link Collections#sort(List,Comparator) Collections.sort} or {@link 38 * Arrays#sort(Object[],Comparator) Arrays.sort}) to allow precise control 39 * over the sort order. Comparators can also be used to control the order of 40 * certain data structures (such as {@link SortedSet sorted sets} or {@link 41 * SortedMap sorted maps}), or to provide an ordering for collections of 42 * objects that don't have a {@link Comparable natural ordering}.<p> 43 * 44 * The ordering imposed by a comparator {@code c} on a set of elements 45 * {@code S} is said to be <i>consistent with equals</i> if and only if 46 * {@code c.compare(e1, e2)==0} has the same boolean value as 47 * {@code e1.equals(e2)} for every {@code e1} and {@code e2} in 48 * {@code S}.<p> 49 * 50 * Caution should be exercised when using a comparator capable of imposing an 51 * ordering inconsistent with equals to order a sorted set (or sorted map). 52 * Suppose a sorted set (or sorted map) with an explicit comparator {@code c} 53 * is used with elements (or keys) drawn from a set {@code S}. If the 54 * ordering imposed by {@code c} on {@code S} is inconsistent with equals, 55 * the sorted set (or sorted map) will behave "strangely." In particular the 56 * sorted set (or sorted map) will violate the general contract for set (or 57 * map), which is defined in terms of {@code equals}.<p> 58 * 59 * For example, suppose one adds two elements {@code a} and {@code b} such that 60 * {@code (a.equals(b) && c.compare(a, b) != 0)} 61 * to an empty {@code TreeSet} with comparator {@code c}. 62 * The second {@code add} operation will return 63 * true (and the size of the tree set will increase) because {@code a} and 64 * {@code b} are not equivalent from the tree set's perspective, even though 65 * this is contrary to the specification of the 66 * {@link Set#add Set.add} method.<p> 67 * 68 * Note: It is generally a good idea for comparators to also implement 69 * {@code java.io.Serializable}, as they may be used as ordering methods in 70 * serializable data structures (like {@link TreeSet}, {@link TreeMap}). In 71 * order for the data structure to serialize successfully, the comparator (if 72 * provided) must implement {@code Serializable}.<p> 73 * 74 * For the mathematically inclined, the <i>relation</i> that defines the 75 * <i>imposed ordering</i> that a given comparator {@code c} imposes on a 76 * given set of objects {@code S} is:<pre> 77 * {(x, y) such that c.compare(x, y) <= 0}. 78 * </pre> The <i>quotient</i> for this total order is:<pre> 79 * {(x, y) such that c.compare(x, y) == 0}. 80 * </pre> 81 * 82 * It follows immediately from the contract for {@code compare} that the 83 * quotient is an <i>equivalence relation</i> on {@code S}, and that the 84 * imposed ordering is a <i>total order</i> on {@code S}. When we say that 85 * the ordering imposed by {@code c} on {@code S} is <i>consistent with 86 * equals</i>, we mean that the quotient for the ordering is the equivalence 87 * relation defined by the objects' {@link Object#equals(Object) 88 * equals(Object)} method(s):<pre> 89 * {(x, y) such that x.equals(y)}. </pre> 90 * 91 * <p>Unlike {@code Comparable}, a comparator may optionally permit 92 * comparison of null arguments, while maintaining the requirements for 93 * an equivalence relation. 94 * 95 * <p>This interface is a member of the 96 * <a href="{@docRoot}/java/util/package-summary.html#CollectionsFramework"> 97 * Java Collections Framework</a>. 98 * 99 * @param <T> the type of objects that may be compared by this comparator 100 * 101 * @author Josh Bloch 102 * @author Neal Gafter 103 * @see Comparable 104 * @see java.io.Serializable 105 * @since 1.2 106 */ 107 @FunctionalInterface 108 public interface Comparator<T> { 109 /** 110 * Compares its two arguments for order. Returns a negative integer, 111 * zero, or a positive integer as the first argument is less than, equal 112 * to, or greater than the second.<p> 113 * 114 * The implementor must ensure that {@code sgn(compare(x, y)) == 115 * -sgn(compare(y, x))} for all {@code x} and {@code y}. (This 116 * implies that {@code compare(x, y)} must throw an exception if and only 117 * if {@code compare(y, x)} throws an exception.)<p> 118 * 119 * The implementor must also ensure that the relation is transitive: 120 * {@code ((compare(x, y)>0) && (compare(y, z)>0))} implies 121 * {@code compare(x, z)>0}.<p> 122 * 123 * Finally, the implementor must ensure that {@code compare(x, y)==0} 124 * implies that {@code sgn(compare(x, z))==sgn(compare(y, z))} for all 125 * {@code z}.<p> 126 * 127 * It is generally the case, but <i>not</i> strictly required that 128 * {@code (compare(x, y)==0) == (x.equals(y))}. Generally speaking, 129 * any comparator that violates this condition should clearly indicate 130 * this fact. The recommended language is "Note: this comparator 131 * imposes orderings that are inconsistent with equals."<p> 132 * 133 * In the foregoing description, the notation 134 * {@code sgn(}<i>expression</i>{@code )} designates the mathematical 135 * <i>signum</i> function, which is defined to return one of {@code -1}, 136 * {@code 0}, or {@code 1} according to whether the value of 137 * <i>expression</i> is negative, zero, or positive, respectively. 138 * 139 * @param o1 the first object to be compared. 140 * @param o2 the second object to be compared. 141 * @return a negative integer, zero, or a positive integer as the 142 * first argument is less than, equal to, or greater than the 143 * second. 144 * @throws NullPointerException if an argument is null and this 145 * comparator does not permit null arguments 146 * @throws ClassCastException if the arguments' types prevent them from 147 * being compared by this comparator. 148 */ 149 int compare(T o1, T o2); 150 151 /** 152 * Indicates whether some other object is "equal to" this 153 * comparator. This method must obey the general contract of 154 * {@link Object#equals(Object)}. Additionally, this method can return 155 * {@code true} <i>only</i> if the specified object is also a comparator 156 * and it imposes the same ordering as this comparator. Thus, 157 * {@code comp1.equals(comp2)} implies that {@code sgn(comp1.compare(o1, 158 * o2))==sgn(comp2.compare(o1, o2))} for every object reference 159 * {@code o1} and {@code o2}.<p> 160 * 161 * Note that it is <i>always</i> safe <i>not</i> to override 162 * {@code Object.equals(Object)}. However, overriding this method may, 163 * in some cases, improve performance by allowing programs to determine 164 * that two distinct comparators impose the same order. 165 * 166 * @param obj the reference object with which to compare. 167 * @return {@code true} only if the specified object is also 168 * a comparator and it imposes the same ordering as this 169 * comparator. 170 * @see Object#equals(Object) 171 * @see Object#hashCode() 172 */ 173 boolean equals(Object obj); 174 175 /** 176 * Returns a comparator that imposes the reverse ordering of this 177 * comparator. 178 * 179 * @return a comparator that imposes the reverse ordering of this 180 * comparator. 181 * @since 1.8 182 */ 183 default Comparator<T> reversed() { 184 return Collections.reverseOrder(this); 185 } 186 187 /** 188 * Returns a lexicographic-order comparator with another comparator. 189 * If this {@code Comparator} considers two elements equal, i.e. 190 * {@code compare(a, b) == 0}, {@code other} is used to determine the order. 191 * 192 * <p>The returned comparator is serializable if the specified comparator 193 * is also serializable. 194 * 195 * @apiNote 196 * For example, to sort a collection of {@code String} based on the length 197 * and then case-insensitive natural ordering, the comparator can be 198 * composed using following code, 199 * 200 * <pre>{@code 201 * Comparator<String> cmp = Comparator.comparingInt(String::length) 202 * .thenComparing(String.CASE_INSENSITIVE_ORDER); 203 * }</pre> 204 * 205 * @param other the other comparator to be used when this comparator 206 * compares two objects that are equal. 207 * @return a lexicographic-order comparator composed of this and then the 208 * other comparator 209 * @throws NullPointerException if the argument is null. 210 * @since 1.8 211 */ 212 default Comparator<T> thenComparing(Comparator<? super T> other) { 213 Objects.requireNonNull(other); 214 return (Comparator<T> & Serializable) (c1, c2) -> { 215 int res = compare(c1, c2); 216 return (res != 0) ? res : other.compare(c1, c2); 217 }; 218 } 219 220 /** 221 * Returns a lexicographic-order comparator with a function that 222 * extracts a key to be compared with the given {@code Comparator}. 223 * 224 * @implSpec This default implementation behaves as if {@code 225 * thenComparing(comparing(keyExtractor, cmp))}. 226 * 227 * @param <U> the type of the sort key 228 * @param keyExtractor the function used to extract the sort key 229 * @param keyComparator the {@code Comparator} used to compare the sort key 230 * @return a lexicographic-order comparator composed of this comparator 231 * and then comparing on the key extracted by the keyExtractor function 232 * @throws NullPointerException if either argument is null. 233 * @see #comparing(Function, Comparator) 234 * @see #thenComparing(Comparator) 235 * @since 1.8 236 */ 237 default <U> Comparator<T> thenComparing( 238 Function<? super T, ? extends U> keyExtractor, 239 Comparator<? super U> keyComparator) 240 { 241 return thenComparing(comparing(keyExtractor, keyComparator)); 242 } 243 244 /** 245 * Returns a lexicographic-order comparator with a function that 246 * extracts a {@code Comparable} sort key. 247 * 248 * @implSpec This default implementation behaves as if {@code 249 * thenComparing(comparing(keyExtractor))}. 250 * 251 * @param <U> the type of the {@link Comparable} sort key 252 * @param keyExtractor the function used to extract the {@link 253 * Comparable} sort key 254 * @return a lexicographic-order comparator composed of this and then the 255 * {@link Comparable} sort key. 256 * @throws NullPointerException if the argument is null. 257 * @see #comparing(Function) 258 * @see #thenComparing(Comparator) 259 * @since 1.8 260 */ 261 default <U extends Comparable<? super U>> Comparator<T> thenComparing( 262 Function<? super T, ? extends U> keyExtractor) 263 { 264 return thenComparing(comparing(keyExtractor)); 265 } 266 267 /** 268 * Returns a lexicographic-order comparator with a function that 269 * extracts an {@code int} sort key. 270 * 271 * @implSpec This default implementation behaves as if {@code 272 * thenComparing(comparingInt(keyExtractor))}. 273 * 274 * @param keyExtractor the function used to extract the integer sort key 275 * @return a lexicographic-order comparator composed of this and then the 276 * {@code int} sort key 277 * @throws NullPointerException if the argument is null. 278 * @see #comparingInt(ToIntFunction) 279 * @see #thenComparing(Comparator) 280 * @since 1.8 281 */ 282 default Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor) { 283 return thenComparing(comparingInt(keyExtractor)); 284 } 285 286 /** 287 * Returns a lexicographic-order comparator with a function that 288 * extracts a {@code long} sort key. 289 * 290 * @implSpec This default implementation behaves as if {@code 291 * thenComparing(comparingLong(keyExtractor))}. 292 * 293 * @param keyExtractor the function used to extract the long sort key 294 * @return a lexicographic-order comparator composed of this and then the 295 * {@code long} sort key 296 * @throws NullPointerException if the argument is null. 297 * @see #comparingLong(ToLongFunction) 298 * @see #thenComparing(Comparator) 299 * @since 1.8 300 */ 301 default Comparator<T> thenComparingLong(ToLongFunction<? super T> keyExtractor) { 302 return thenComparing(comparingLong(keyExtractor)); 303 } 304 305 /** 306 * Returns a lexicographic-order comparator with a function that 307 * extracts a {@code double} sort key. 308 * 309 * @implSpec This default implementation behaves as if {@code 310 * thenComparing(comparingDouble(keyExtractor))}. 311 * 312 * @param keyExtractor the function used to extract the double sort key 313 * @return a lexicographic-order comparator composed of this and then the 314 * {@code double} sort key 315 * @throws NullPointerException if the argument is null. 316 * @see #comparingDouble(ToDoubleFunction) 317 * @see #thenComparing(Comparator) 318 * @since 1.8 319 */ 320 default Comparator<T> thenComparingDouble(ToDoubleFunction<? super T> keyExtractor) { 321 return thenComparing(comparingDouble(keyExtractor)); 322 } 323 324 /** 325 * Returns a comparator that imposes the reverse of the <em>natural 326 * ordering</em>. 327 * 328 * <p>The returned comparator is serializable and throws {@link 329 * NullPointerException} when comparing {@code null}. 330 * 331 * @param <T> the {@link Comparable} type of element to be compared 332 * @return a comparator that imposes the reverse of the <i>natural 333 * ordering</i> on {@code Comparable} objects. 334 * @see Comparable 335 * @since 1.8 336 */ 337 public static <T extends Comparable<? super T>> Comparator<T> reverseOrder() { 338 return Collections.reverseOrder(); 339 } 340 341 /** 342 * Returns a comparator that compares {@link Comparable} objects in natural 343 * order. 344 * 345 * <p>The returned comparator is serializable and throws {@link 346 * NullPointerException} when comparing {@code null}. 347 * 348 * @param <T> the {@link Comparable} type of element to be compared 349 * @return a comparator that imposes the <i>natural ordering</i> on {@code 350 * Comparable} objects. 351 * @see Comparable 352 * @since 1.8 353 */ 354 @SuppressWarnings("unchecked") 355 public static <T extends Comparable<? super T>> Comparator<T> naturalOrder() { 356 return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE; 357 } 358 359 /** 360 * Returns a null-friendly comparator that considers {@code null} to be 361 * less than non-null. When both are {@code null}, they are considered 362 * equal. If both are non-null, the specified {@code Comparator} is used 363 * to determine the order. If the specified comparator is {@code null}, 364 * then the returned comparator considers all non-null values to be equal. 365 * 366 * <p>The returned comparator is serializable if the specified comparator 367 * is serializable. 368 * 369 * @param <T> the type of the elements to be compared 370 * @param comparator a {@code Comparator} for comparing non-null values 371 * @return a comparator that considers {@code null} to be less than 372 * non-null, and compares non-null objects with the supplied 373 * {@code Comparator}. 374 * @since 1.8 375 */ 376 public static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator) { 377 return new Comparators.NullComparator<>(true, comparator); 378 } 379 380 /** 381 * Returns a null-friendly comparator that considers {@code null} to be 382 * greater than non-null. When both are {@code null}, they are considered 383 * equal. If both are non-null, the specified {@code Comparator} is used 384 * to determine the order. If the specified comparator is {@code null}, 385 * then the returned comparator considers all non-null values to be equal. 386 * 387 * <p>The returned comparator is serializable if the specified comparator 388 * is serializable. 389 * 390 * @param <T> the type of the elements to be compared 391 * @param comparator a {@code Comparator} for comparing non-null values 392 * @return a comparator that considers {@code null} to be greater than 393 * non-null, and compares non-null objects with the supplied 394 * {@code Comparator}. 395 * @since 1.8 396 */ 397 public static <T> Comparator<T> nullsLast(Comparator<? super T> comparator) { 398 return new Comparators.NullComparator<>(false, comparator); 399 } 400 401 /** 402 * Accepts a function that extracts a sort key from a type {@code T}, and 403 * returns a {@code Comparator<T>} that compares by that sort key using 404 * the specified {@link Comparator}. 405 * 406 * <p>The returned comparator is serializable if the specified function 407 * and comparator are both serializable. 408 * 409 * @apiNote 410 * For example, to obtain a {@code Comparator} that compares {@code 411 * Person} objects by their last name ignoring case differences, 412 * 413 * <pre>{@code 414 * Comparator<Person> cmp = Comparator.comparing( 415 * Person::getLastName, 416 * String.CASE_INSENSITIVE_ORDER); 417 * }</pre> 418 * 419 * @param <T> the type of element to be compared 420 * @param <U> the type of the sort key 421 * @param keyExtractor the function used to extract the sort key 422 * @param keyComparator the {@code Comparator} used to compare the sort key 423 * @return a comparator that compares by an extracted key using the 424 * specified {@code Comparator} 425 * @throws NullPointerException if either argument is null 426 * @since 1.8 427 */ 428 public static <T, U> Comparator<T> comparing( 429 Function<? super T, ? extends U> keyExtractor, 430 Comparator<? super U> keyComparator) 431 { 432 Objects.requireNonNull(keyExtractor); 433 Objects.requireNonNull(keyComparator); 434 return (Comparator<T> & Serializable) 435 (c1, c2) -> keyComparator.compare(keyExtractor.apply(c1), 436 keyExtractor.apply(c2)); 437 } 438 439 /** 440 * Accepts a function that extracts a {@link java.lang.Comparable 441 * Comparable} sort key from a type {@code T}, and returns a {@code 442 * Comparator<T>} that compares by that sort key. 443 * 444 * <p>The returned comparator is serializable if the specified function 445 * is also serializable. 446 * 447 * @apiNote 448 * For example, to obtain a {@code Comparator} that compares {@code 449 * Person} objects by their last name, 450 * 451 * <pre>{@code 452 * Comparator<Person> byLastName = Comparator.comparing(Person::getLastName); 453 * }</pre> 454 * 455 * @param <T> the type of element to be compared 456 * @param <U> the type of the {@code Comparable} sort key 457 * @param keyExtractor the function used to extract the {@link 458 * Comparable} sort key 459 * @return a comparator that compares by an extracted key 460 * @throws NullPointerException if the argument is null 461 * @since 1.8 462 */ 463 public static <T, U extends Comparable<? super U>> Comparator<T> comparing( 464 Function<? super T, ? extends U> keyExtractor) 465 { 466 Objects.requireNonNull(keyExtractor); 467 return (Comparator<T> & Serializable) 468 (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2)); 469 } 470 471 /** 472 * Accepts a function that extracts an {@code int} sort key from a type 473 * {@code T}, and returns a {@code Comparator<T>} that compares by that 474 * sort key. 475 * 476 * <p>The returned comparator is serializable if the specified function 477 * is also serializable. 478 * 479 * @param <T> the type of element to be compared 480 * @param keyExtractor the function used to extract the integer sort key 481 * @return a comparator that compares by an extracted key 482 * @see #comparing(Function) 483 * @throws NullPointerException if the argument is null 484 * @since 1.8 485 */ 486 public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) { 487 Objects.requireNonNull(keyExtractor); 488 return (Comparator<T> & Serializable) 489 (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2)); 490 } 491 492 /** 493 * Accepts a function that extracts a {@code long} sort key from a type 494 * {@code T}, and returns a {@code Comparator<T>} that compares by that 495 * sort key. 496 * 497 * <p>The returned comparator is serializable if the specified function is 498 * also serializable. 499 * 500 * @param <T> the type of element to be compared 501 * @param keyExtractor the function used to extract the long sort key 502 * @return a comparator that compares by an extracted key 503 * @see #comparing(Function) 504 * @throws NullPointerException if the argument is null 505 * @since 1.8 506 */ 507 public static <T> Comparator<T> comparingLong(ToLongFunction<? super T> keyExtractor) { 508 Objects.requireNonNull(keyExtractor); 509 return (Comparator<T> & Serializable) 510 (c1, c2) -> Long.compare(keyExtractor.applyAsLong(c1), keyExtractor.applyAsLong(c2)); 511 } 512 513 /** 514 * Accepts a function that extracts a {@code double} sort key from a type 515 * {@code T}, and returns a {@code Comparator<T>} that compares by that 516 * sort key. 517 * 518 * <p>The returned comparator is serializable if the specified function 519 * is also serializable. 520 * 521 * @param <T> the type of element to be compared 522 * @param keyExtractor the function used to extract the double sort key 523 * @return a comparator that compares by an extracted key 524 * @see #comparing(Function) 525 * @throws NullPointerException if the argument is null 526 * @since 1.8 527 */ 528 public static <T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor) { 529 Objects.requireNonNull(keyExtractor); 530 return (Comparator<T> & Serializable) 531 (c1, c2) -> Double.compare(keyExtractor.applyAsDouble(c1), keyExtractor.applyAsDouble(c2)); 532 } 533 534 /** 535 * The returned comparator compares two character sequences as though each 536 * of them would be first transformed into a tuple of the form: 537 * <pre>{@code (A0, N0, A1, N1, ..., An-1, Nn-1, An, Nn)}</pre> 538 * where: 539 * <p>{@code A0} and {@code An} are (possibly empty) sub-sequences 540 * consisting of non-decimal-digit characters, 541 * <p>{@code A1 ... An-1} are non-empty sub-sequences consisting of 542 * non-decimal-digit characters, 543 * <p>{@code N0 ... Nn-1} are non-empty sub-sequences consisting of 544 * decimal-digit characters, and 545 * <p>{@code Nn} is a (possibly empty) sub-sequence consisting of 546 * decimal-digit characters. 547 * 548 * <p>All sub-sequences concatenated together in order as they appear in the 549 * tuple yield the original character sequence. 550 * 551 * After transformation, the tuples are compared by their elements (from 552 * left to right) so that corresponding {@code Ax} elements are compared 553 * using the provided comparator {@code alphaComparator} and {@code Nx} 554 * elements are compared as non negative decimal integers. 555 * 556 * The first pair of compared elements that is different with respect to the 557 * used comparator (either {@code alphaComparator}, or special decimal 558 * comparator) if any, provides the result produced by this comparator. 559 * The arguments are treated equal, if and only if all the subsequences, 560 * both decimal and non-decimal, compare equal. 561 * 562 * <p>For example, the following array was sorted using such comparator: 563 * <pre>{@code 564 * { "1ab", "5ab", "10ab", 565 * "a1b", "a5b", "a10b", 566 * "ab1", "ab5", "ab10" };}</pre> 567 * 568 * <p>When comparing numerical parts, an empty character sequence is 569 * considered less than any non-empty sequence of decimal digits. 570 * 571 * <p>If the numeric values of two compared character sub-sequences are 572 * equal, but their string representations have different number of leading 573 * zeroes, the comparator treats the number with less leading zeros as 574 * smaller. 575 * For example, {@code "abc 1" < "abc 01" < "abc 001"}. 576 * 577 * @apiNote For example, to sort a collection of {@code String} based on 578 * case-insensitive ordering, and treating numbers with more leading 579 * zeroes as greater, one could use 580 * 581 * <pre>{@code 582 * Comparator<String> cmp = Comparator.comparingAlphaDecimal( 583 * Comparator.comparing(CharSequence::toString, 584 * String::compareToIgnoreCase)); 585 * }</pre> 586 * 587 * @implSpec To test if the given code point represents a decimal digit, 588 * the comparator checks if {@link java.lang.Character#getType(int)} 589 * returns value {@link java.lang.Character#DECIMAL_DIGIT_NUMBER}. 590 * The comparator uses {@link java.lang.Character#digit(int, int)} with 591 * the second argument set to {@code 10} to determine the numeric 592 * value of a digit represented by the given code point. 593 * 594 * @param alphaComparator the comparator that compares sub-sequences 595 * consisting of non-decimal-digits 596 * @param <T> the type of elements to be compared; normally 597 * {@link java.lang.CharSequence} 598 * @return a comparator that compares character sequences, following the 599 * rules described above 600 * @throws NullPointerException if the argument is null 601 * 602 * @since 10 603 */ 604 public static <T extends CharSequence> Comparator<T> 605 comparingAlphaDecimal(Comparator<? super CharSequence> alphaComparator) { 606 return new Comparators.AlphaDecimalComparator<>( 607 Objects.requireNonNull(alphaComparator), false); 608 } 609 610 /** 611 * The returned comparator compares two character sequences as though each 612 * of them would be first transformed into a tuple of the form: 613 * <pre>{@code (A0, N0, A1, N1, ..., An-1, Nn-1, An, Nn)}</pre> 614 * where: 615 * <p>{@code A0} and {@code An} are (possibly empty) sub-sequences 616 * consisting of non-decimal-digit characters, 617 * <p>{@code A1 ... An-1} are non-empty sub-sequences consisting of 618 * non-decimal-digit characters, 619 * <p>{@code N0 ... Nn-1} are non-empty sub-sequences consisting of 620 * decimal-digit characters, and 621 * <p>{@code Nn} is a (possibly empty) sub-sequence consisting of 622 * decimal-digit characters. 623 * 624 * <p>All sub-sequences concatenated together in order as they appear in the 625 * tuple yield the original character sequence. 626 * 627 * After transformation, the tuples are compared by their elements (from 628 * left to right) so that corresponding {@code Ax} elements are compared 629 * using the provided comparator {@code alphaComparator} and {@code Nx} 630 * elements are compared as non negative decimal integers. 631 * 632 * The first pair of compared elements that is different with respect to the 633 * used comparator (either {@code alphaComparator}, or special decimal 634 * comparator) if any, provides the result produced by this comparator. 635 * The arguments are treated equal, if and only if all the subsequences, 636 * both decimal and non-decimal, compare equal. 637 * 638 * <p>For example, the following array was sorted using such comparator: 639 * <pre>{@code 640 * { "1ab", "5ab", "10ab", 641 * "a1b", "a5b", "a10b", 642 * "ab1", "ab5", "ab10" };}</pre> 643 * 644 * <p>When comparing numerical parts, an empty character sequence is 645 * considered less than any non-empty sequence of decimal digits. 646 * 647 * <p>If the numeric values of two compared character sub-sequences are 648 * equal, but their string representations have different number of leading 649 * zeroes, the comparator treats the number with more leading zeros as 650 * smaller. 651 * For example, {@code "abc 001" < "abc 01" < "abc 1"}. 652 * 653 * @apiNote For example, to sort a collection of {@code String} based on 654 * case-insensitive ordering, and treating numbers with less leading 655 * zeroes as greater, one could use 656 * 657 * <pre>{@code 658 * Comparator<String> cmp = Comparator.comparingAlphaDecimalLeadingZeroesFirst( 659 * Comparator.comparing(CharSequence::toString, 660 * String::compareToIgnoreCase)); 661 * }</pre> 662 * 663 * @implSpec To test if the given code point represents a decimal digit, 664 * the comparator checks if {@link java.lang.Character#getType(int)} 665 * returns value {@link java.lang.Character#DECIMAL_DIGIT_NUMBER}. 666 * The comparator uses {@link java.lang.Character#digit(int, int)} with 667 * the second argument set to {@code 10} to determine the numeric 668 * value of a digit represented by the given code point. 669 * 670 * @param alphaComparator the comparator that compares sub-sequences 671 * consisting of non-decimal-digits 672 * @param <T> the type of elements to be compared; normally 673 * {@link java.lang.CharSequence} 674 * @return a comparator that compares character sequences, following the 675 * rules described above 676 * @throws NullPointerException if the argument is null 677 * 678 * @since 10 679 */ 680 public static <T extends CharSequence> Comparator<T> 681 comparingAlphaDecimalLeadingZeroesFirst( 682 Comparator<? super CharSequence> alphaComparator) { 683 return new Comparators.AlphaDecimalComparator<>( 684 Objects.requireNonNull(alphaComparator), true); 685 } 686 }