src/share/classes/java/util/Comparator.java

Print this page
rev 7485 : 8009736: Comparator API cleanup
Reviewed-by:
Contributed-by: henry.jen@oracle.com


   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.util.function.Function;
  29 import java.util.function.ToIntFunction;
  30 import java.util.function.ToLongFunction;
  31 import java.util.function.ToDoubleFunction;

  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>


 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> reverseOrder() {
 183         return Collections.reverseOrder(this);
 184     }
 185 
 186     /**
 187      * Constructs a lexicographic order comparator with another comparator.
 188      * For example, a {@code Comparator<Person> byLastName} can be composed
 189      * with another {@code Comparator<Person> byFirstName}, then {@code
 190      * byLastName.thenComparing(byFirstName)} creates a {@code
 191      * Comparator<Person>} which sorts by last name, and for equal last names
 192      * sorts by first name.
 193      *
 194      * @param other the other comparator used when equals on this.
















 195      * @throws NullPointerException if the argument is null.
 196      * @since 1.8
 197      */
 198     default Comparator<T> thenComparing(Comparator<? super T> other) {
 199         return Comparators.compose(this, other);




 200     }
 201 
 202     /**
 203      * Constructs a lexicographic order comparator with a function that
 204      * extracts a {@code Comparable} key.  This default implementation calls
 205      * {@code thenComparing(this, Comparators.comparing(keyExtractor))}.


 206      *
 207      * @param <U> the {@link Comparable} type for comparison
 208      * @param keyExtractor the function used to extract the {@link Comparable} sort key



 209      * @throws NullPointerException if the argument is null.
 210      * @see Comparators#comparing(Function)
 211      * @see #thenComparing(Comparator)
 212      * @since 1.8
 213      */
 214     default <U extends Comparable<? super U>> Comparator<T> thenComparing(Function<? super T, ? extends U> keyExtractor) {
 215         return thenComparing(Comparators.comparing(keyExtractor));



 216     }
 217 
 218     /**
 219      * Constructs a lexicographic order comparator with a function that
 220      * extracts a {@code int} value.  This default implementation calls {@code
 221      * thenComparing(this, Comparators.comparing(keyExtractor))}.


 222      *
 223      * @param keyExtractor the function used to extract the integer value




 224      * @throws NullPointerException if the argument is null.
 225      * @see Comparators#comparing(ToIntFunction)





















 226      * @see #thenComparing(Comparator)
 227      * @since 1.8
 228      */
 229     default Comparator<T> thenComparing(ToIntFunction<? super T> keyExtractor) {
 230         return thenComparing(Comparators.comparing(keyExtractor));
 231     }
 232 
 233     /**
 234      * Constructs a lexicographic order comparator with a function that
 235      * extracts a {@code long} value.  This default implementation calls
 236      * {@code thenComparing(this, Comparators.comparing(keyExtractor))}.
 237      *
 238      * @param keyExtractor the function used to extract the long value





 239      * @throws NullPointerException if the argument is null.
 240      * @see Comparators#comparing(ToLongFunction)
 241      * @see #thenComparing(Comparator)
 242      * @since 1.8
 243      */
 244     default Comparator<T> thenComparing(ToLongFunction<? super T> keyExtractor) {
 245         return thenComparing(Comparators.comparing(keyExtractor));
 246     }
 247 
 248     /**
 249      * Constructs a lexicographic order comparator with a function that
 250      * extracts a {@code double} value.  This default implementation calls
 251      * {@code thenComparing(this, Comparators.comparing(keyExtractor))}.


 252      *
 253      * @param keyExtractor the function used to extract the double value


 254      * @throws NullPointerException if the argument is null.
 255      * @see Comparators#comparing(ToDoubleFunction)
 256      * @see #thenComparing(Comparator)
 257      * @since 1.8
 258      */
 259     default Comparator<T> thenComparing(ToDoubleFunction<? super T> keyExtractor) {
 260         return thenComparing(Comparators.comparing(keyExtractor));















































































































































































































 261     }
 262 }


   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 import java.util.Comparators;
  34 
  35 /**
  36  * A comparison function, which imposes a <i>total ordering</i> on some
  37  * collection of objects.  Comparators can be passed to a sort method (such
  38  * as {@link Collections#sort(List,Comparator) Collections.sort} or {@link
  39  * Arrays#sort(Object[],Comparator) Arrays.sort}) to allow precise control
  40  * over the sort order.  Comparators can also be used to control the order of
  41  * certain data structures (such as {@link SortedSet sorted sets} or {@link
  42  * SortedMap sorted maps}), or to provide an ordering for collections of
  43  * objects that don't have a {@link Comparable natural ordering}.<p>
  44  *
  45  * The ordering imposed by a comparator <tt>c</tt> on a set of elements
  46  * <tt>S</tt> is said to be <i>consistent with equals</i> if and only if
  47  * <tt>c.compare(e1, e2)==0</tt> has the same boolean value as
  48  * <tt>e1.equals(e2)</tt> for every <tt>e1</tt> and <tt>e2</tt> in
  49  * <tt>S</tt>.<p>
  50  *
  51  * Caution should be exercised when using a comparator capable of imposing an
  52  * ordering inconsistent with equals to order a sorted set (or sorted map).
  53  * Suppose a sorted set (or sorted map) with an explicit comparator <tt>c</tt>


 164      * in some cases, improve performance by allowing programs to determine
 165      * that two distinct comparators impose the same order.
 166      *
 167      * @param   obj   the reference object with which to compare.
 168      * @return  <code>true</code> only if the specified object is also
 169      *          a comparator and it imposes the same ordering as this
 170      *          comparator.
 171      * @see Object#equals(Object)
 172      * @see Object#hashCode()
 173      */
 174     boolean equals(Object obj);
 175 
 176     /**
 177      * Returns a comparator that imposes the reverse ordering of this
 178      * comparator.
 179      *
 180      * @return A comparator that imposes the reverse ordering of this
 181      *         comparator.
 182      * @since 1.8
 183      */
 184     default Comparator<T> reversed() {
 185         return Collections.reverseOrder(this);
 186     }
 187 
 188     /**
 189      * Constructs a lexicographic order comparator with another comparator.
 190      * If this {@code Comparator} considers two elements equal, i.e.
 191      * {@code compare(a, b) == 0}, {@code other} is used to determine the order.



 192      *
 193      * <p>The returned comparator is serializable if the specified comparator
 194      * is also serializable.
 195      *
 196      * @apiNote
 197      * To sort a collection of {@code String} based on the length and then
 198      * case-insensitive natural ordering, the comparator can be construcred
 199      * using following code,
 200      *
 201      * <pre>{@code
 202      *     Comparator<String> cmp = Comparator.comparing(String::length)
 203      *             .thenComparing(String.CASE_INSENSITIVE_ORDER);
 204      * }</pre>
 205      *
 206      * @param  other the other comparator to be used when this comparator
 207      *         compares two objects that are equal.
 208      * @return A lexicographic order comparator composed of this and then the
 209      *         other comparator
 210      * @throws NullPointerException if the argument is null.
 211      * @since 1.8
 212      */
 213     default Comparator<T> thenComparing(Comparator<? super T> other) {
 214         Objects.requireNonNull(other);
 215         return (Comparator<T> & Serializable) (c1, c2) -> {
 216             int res = compare(c1, c2);
 217             return (res != 0) ? res : other.compare(c1, c2);
 218         };
 219     }
 220 
 221     /**
 222      * Constructs a lexicographic order comparator with a function that
 223      * extracts a key to be compared with the given {@code Comparator}.
 224      *
 225      * @implSpec This default implementation calls {@code
 226      *           thenComparing(comparing(keyExtractor, cmp))}.
 227      *
 228      * @param  <U>  The type of the sort key
 229      * @param  keyExtractor the function used to extract the sort key
 230      * @param  keyComparator the {@code Comparator} used to compare the sort key
 231      * @return A lexicographic order comparator composed of this and then the
 232      *         key comparator.
 233      * @throws NullPointerException if the argument is null.
 234      * @see #comparing(Function, Comparator)
 235      * @see #thenComparing(Comparator)
 236      * @since 1.8
 237      */
 238     default <U extends Comparable<? super U>> Comparator<T> thenComparing(
 239             Function<? super T, ? extends U> keyExtractor,
 240             Comparator<? super U> keyComparator)
 241     {
 242         return thenComparing(comparing(keyExtractor, keyComparator));
 243     }
 244 
 245     /**
 246      * Constructs a lexicographic order comparator with a function that
 247      * extracts a {@code Comparable} sort key.
 248      *
 249      * @implSpec This default implementation calls {@code
 250      *           thenComparing(comparing(keyExtractor))}.
 251      *
 252      * @param  <U>  The type of the {@link Comparable} sort key
 253      * @param  keyExtractor the function used to extract the {@link
 254      *         Comparable} sort key
 255      * @return A lexicographic order comparator composed of this and then the
 256      *         {@link Comparable} sort key.
 257      * @throws NullPointerException if the argument is null.
 258      * @see #comparing(Function)
 259      * @see #thenComparing(Comparator)
 260      * @since 1.8
 261      */
 262     default <U extends Comparable<? super U>> Comparator<T> thenComparing(
 263             Function<? super T, ? extends U> keyExtractor)
 264     {
 265         return thenComparing(comparing(keyExtractor));
 266     }
 267 
 268     /**
 269      * Constructs a lexicographic order comparator with a function that
 270      * extracts a {@code int} sort key.
 271      *
 272      * @implSpec This default implementation calls {@code
 273      *           thenComparing(comparing(keyExtractor))}.
 274      *
 275      * @param  keyExtractor the function used to extract the integer sort key
 276      * @return A lexicographic order comparator composed of this and then the
 277      *         {@code int} sort key
 278      * @throws NullPointerException if the argument is null.
 279      * @see #comparing(ToIntFunction)
 280      * @see #thenComparing(Comparator)
 281      * @since 1.8
 282      */
 283     default Comparator<T> thenComparing(ToIntFunction<? super T> keyExtractor) {
 284         return thenComparing(comparing(keyExtractor));
 285     }
 286 
 287     /**
 288      * Constructs a lexicographic order comparator with a function that
 289      * extracts a {@code long} sort key.

 290      *
 291      * @implSpec This default implementation calls {@code
 292      *           thenComparing(comparing(keyExtractor))}.
 293      *
 294      * @param  keyExtractor the function used to extract the long sort key
 295      * @return A lexicographic order comparator composed of this and then the
 296      *         {@code long} sort key
 297      * @throws NullPointerException if the argument is null.
 298      * @see #comparing(ToLongFunction)
 299      * @see #thenComparing(Comparator)
 300      * @since 1.8
 301      */
 302     default Comparator<T> thenComparing(ToLongFunction<? super T> keyExtractor) {
 303         return thenComparing(comparing(keyExtractor));
 304     }
 305 
 306     /**
 307      * Constructs a lexicographic order comparator with a function that
 308      * extracts a {@code double} sort key.
 309      *
 310      * @implSpec This default implementation calls {@code
 311      *           thenComparing(comparing(keyExtractor))}.
 312      *
 313      * @param  keyExtractor the function used to extract the double sort key
 314      * @return A lexicographic order comparator composed of this and then the
 315      *         {@code double} sort key
 316      * @throws NullPointerException if the argument is null.
 317      * @see #comparing(ToDoubleFunction)
 318      * @see #thenComparing(Comparator)
 319      * @since 1.8
 320      */
 321     default Comparator<T> thenComparing(ToDoubleFunction<? super T> keyExtractor) {
 322         return thenComparing(comparing(keyExtractor));
 323     }
 324 
 325     /**
 326      * Returns a comparator that imposes the reverse of the <em>natural
 327      * ordering</em>.
 328      *
 329      * <p>The returned comparator is serializable and throws {@link
 330      * NullPointerException} when comparing {@code null}.
 331      *
 332      * @param  <T> The {@link Comparable} type of element to be compared
 333      * @return A comparator that imposes the reverse of the <i>natural
 334      *         ordering</i> on a collection of objects that implement
 335      *         the {@link Comparable} interface.
 336      * @see Comparable
 337      * @since 1.8
 338      */
 339     public static <T extends Comparable<? super T>> Comparator<T> reverseOrder() {
 340         return Collections.reverseOrder();
 341     }
 342 
 343     /**
 344      * Returns a comparator that compares {@link Comparable} type in natural
 345      * order.
 346      *
 347      * <p>The returned comparator is serializable and throws {@link
 348      * NullPointerException} when comparing {@code null}.
 349      *
 350      * @param  <T> The {@link Comparable} type of element to be compared
 351      * @return A comparator that imposes the <i>natural ordering</i> on a
 352      *         collection of objects that implement the {@link Comparable}
 353      *         interface.
 354      * @see Comparable
 355      * @since 1.8
 356      */
 357     public static <T extends Comparable<? super T>> Comparator<T> naturalOrder() {
 358         return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE;
 359     }
 360 
 361     /**
 362      * Returns a null-friendly comparator that considers {@code null} to be
 363      * less than non-null. When both are {@code null}, they are considered
 364      * equal. If both are non-null, the specified {@code Comparator} is used
 365      * to determine the order. If the specified comparator is {@code null},
 366      * then the returned comparator considers all non-null values to be equal.
 367      *
 368      * <p>The returned comparator is serializable if the specified comparator
 369      * is serializable.
 370      *
 371      * @param  <T> the type of the elements to be compared
 372      * @param  comparator A {@code Comparator} for comparing non-null values
 373      * @return A comparator that considers {@code null} to be less than non-null.
 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 non-null.
 393      * @since 1.8
 394      */
 395     public static <T> Comparator<T> nullsLast(Comparator<? super T> comparator) {
 396         return new Comparators.NullComparator(false, comparator);
 397     }
 398 
 399     /**
 400      * Accepts a function that extracts a sort key from a type {@code T}, and
 401      * returns a {@code Comparator<T>} that compares by that sort key using
 402      * the specified {@link Comparator}.
 403       *
 404      * <p>The returned comparator is serializable if the specified function
 405      * and comparator are both serializable.
 406      *
 407      * @apiNote
 408      * To obtain a {@code Comparator} that compares {@code Person} objects by their last name
 409      * ignoring case differences,
 410      *
 411      * <pre>{@code
 412      *     Comparator<People> cmp = Comparator.comparing(
 413      *             Person::getLastName,
 414      *             String.CASE_INSENSITIVE_ORDER);
 415      * }</pre>
 416      *
 417      * @param  <T> The type of element to be compared
 418      * @param  <U> The type of the sort key
 419      * @param  keyExtractor the function used to extract the sort key
 420      * @param  keyComparator the {@code Comparator} used to compare the sort key
 421      * @return A comparator that compares by an extracted key using the
 422      *         specified {@code Comparator}
 423      * @throws NullPointerException if the argument is null
 424      * @since 1.8
 425      */
 426     public static <T, U> Comparator<T> comparing(
 427             Function<? super T, ? extends U> keyExtractor,
 428             Comparator<? super U> keyComparator)
 429     {
 430         Objects.requireNonNull(keyExtractor);
 431         Objects.requireNonNull(keyComparator);
 432         return (Comparator<T> & Serializable)
 433             (c1, c2) -> keyComparator.compare(keyExtractor.apply(c1),
 434                                               keyExtractor.apply(c2));
 435     }
 436 
 437     /**
 438      * Accepts a function that extracts a {@link java.lang.Comparable
 439      * Comparable} sort key from a type {@code T}, and returns a {@code
 440      * Comparator<T>} that compares by that sort key.
 441      *
 442      * <p>The returned comparator is serializable if the specified function
 443      * is also serializable.
 444      *
 445      * @apiNote
 446      * To obtain a {@code Comparator} that compares {@code Person} objects by their last
 447      * name,
 448      *
 449      * <pre>{@code
 450      *     Comparator<People> byLastName = Comparator.comparing(Person::getLastName);
 451      * }</pre>
 452      *
 453      * @param  <T> The type of element to be compared
 454      * @param  <U> The type of the {@code Comparable} sort key
 455      * @param  keyExtractor the function used to extract the {@link
 456      *         Comparable} sort key
 457      * @return A comparator that compares by an extracted key
 458      * @throws NullPointerException if the argument is null
 459      * @since 1.8
 460      */
 461     public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
 462             Function<? super T, ? extends U> keyExtractor)
 463     {
 464         Objects.requireNonNull(keyExtractor);
 465         return (Comparator<T> & Serializable)
 466             (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
 467     }
 468 
 469     /**
 470      * Accepts a function that extracts an {@code int} sort key from a type
 471      * {@code T}, and returns a {@code Comparator<T>} that compares by that
 472      * sort key.
 473      *
 474      * <p>The returned comparator is serializable if the specified function
 475      * is also serializable.
 476      *
 477      * @param  <T> The type of element to be compared
 478      * @param  keyExtractor the function used to extract the integer sort key
 479      * @return A comparator that compares by an extracted key
 480      * @see #comparing(Function)
 481      * @throws NullPointerException if the argument is null
 482      * @since 1.8
 483      */
 484     public static <T> Comparator<T> comparing(ToIntFunction<? super T> keyExtractor) {
 485         Objects.requireNonNull(keyExtractor);
 486         return (Comparator<T> & Serializable)
 487             (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2));
 488     }
 489 
 490     /**
 491      * Accepts a function that extracts a {@code long} sort key from a type
 492      * {@code T}, and returns a {@code Comparator<T>} that compares by that
 493      * sort key.
 494      *
 495      * <p>The returned comparator is serializable if the specified function is
 496      * also serializable.
 497      *
 498      * @param  <T> The type of element to be compared
 499      * @param  keyExtractor the function used to extract the long sort key
 500      * @return A comparator that compares by an extracted key
 501      * @see #comparing(Function)
 502      * @throws NullPointerException if the argument is null
 503      * @since 1.8
 504      */
 505     public static <T> Comparator<T> comparing(ToLongFunction<? super T> keyExtractor) {
 506         Objects.requireNonNull(keyExtractor);
 507         return (Comparator<T> & Serializable)
 508             (c1, c2) -> Long.compare(keyExtractor.applyAsLong(c1), keyExtractor.applyAsLong(c2));
 509     }
 510 
 511     /**
 512      * Accepts a function that extracts a {@code double} sort key from a type
 513      * {@code T}, and returns a {@code Comparator<T>} that compares by that
 514      * sort key.
 515      *
 516      * <p>The returned comparator is serializable if the specified function
 517      * is also serializable.
 518      *
 519      * @param  <T> The type of element to be compared
 520      * @param  keyExtractor the function used to extract the double sort key
 521      * @return A comparator that compares by an extracted key
 522      * @see #comparing(Function)
 523      * @throws NullPointerException if the argument is null
 524      * @since 1.8
 525      */
 526     public static<T> Comparator<T> comparing(ToDoubleFunction<? super T> keyExtractor) {
 527         Objects.requireNonNull(keyExtractor);
 528         return (Comparator<T> & Serializable)
 529             (c1, c2) -> Double.compare(keyExtractor.applyAsDouble(c1), keyExtractor.applyAsDouble(c2));
 530     }
 531 }