Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/util/Comparator.java
38829 views
/*1* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.util;2627import java.io.Serializable;28import java.util.function.Function;29import java.util.function.ToIntFunction;30import java.util.function.ToLongFunction;31import java.util.function.ToDoubleFunction;32import java.util.Comparators;3334/**35* A comparison function, which imposes a <i>total ordering</i> on some36* collection of objects. Comparators can be passed to a sort method (such37* as {@link Collections#sort(List,Comparator) Collections.sort} or {@link38* Arrays#sort(Object[],Comparator) Arrays.sort}) to allow precise control39* over the sort order. Comparators can also be used to control the order of40* certain data structures (such as {@link SortedSet sorted sets} or {@link41* SortedMap sorted maps}), or to provide an ordering for collections of42* objects that don't have a {@link Comparable natural ordering}.<p>43*44* The ordering imposed by a comparator <tt>c</tt> on a set of elements45* <tt>S</tt> is said to be <i>consistent with equals</i> if and only if46* <tt>c.compare(e1, e2)==0</tt> has the same boolean value as47* <tt>e1.equals(e2)</tt> for every <tt>e1</tt> and <tt>e2</tt> in48* <tt>S</tt>.<p>49*50* Caution should be exercised when using a comparator capable of imposing an51* ordering inconsistent with equals to order a sorted set (or sorted map).52* Suppose a sorted set (or sorted map) with an explicit comparator <tt>c</tt>53* is used with elements (or keys) drawn from a set <tt>S</tt>. If the54* ordering imposed by <tt>c</tt> on <tt>S</tt> is inconsistent with equals,55* the sorted set (or sorted map) will behave "strangely." In particular the56* sorted set (or sorted map) will violate the general contract for set (or57* map), which is defined in terms of <tt>equals</tt>.<p>58*59* For example, suppose one adds two elements {@code a} and {@code b} such that60* {@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 return63* true (and the size of the tree set will increase) because {@code a} and64* {@code b} are not equivalent from the tree set's perspective, even though65* this is contrary to the specification of the66* {@link Set#add Set.add} method.<p>67*68* Note: It is generally a good idea for comparators to also implement69* <tt>java.io.Serializable</tt>, as they may be used as ordering methods in70* serializable data structures (like {@link TreeSet}, {@link TreeMap}). In71* order for the data structure to serialize successfully, the comparator (if72* provided) must implement <tt>Serializable</tt>.<p>73*74* For the mathematically inclined, the <i>relation</i> that defines the75* <i>imposed ordering</i> that a given comparator <tt>c</tt> imposes on a76* given set of objects <tt>S</tt> 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 <tt>compare</tt> that the83* quotient is an <i>equivalence relation</i> on <tt>S</tt>, and that the84* imposed ordering is a <i>total order</i> on <tt>S</tt>. When we say that85* the ordering imposed by <tt>c</tt> on <tt>S</tt> is <i>consistent with86* equals</i>, we mean that the quotient for the ordering is the equivalence87* 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 permit92* comparison of null arguments, while maintaining the requirements for93* an equivalence relation.94*95* <p>This interface is a member of the96* <a href="{@docRoot}/../technotes/guides/collections/index.html">97* Java Collections Framework</a>.98*99* @param <T> the type of objects that may be compared by this comparator100*101* @author Josh Bloch102* @author Neal Gafter103* @see Comparable104* @see java.io.Serializable105* @since 1.2106*/107@FunctionalInterface108public 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, equal112* to, or greater than the second.<p>113*114* In the foregoing description, the notation115* <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical116* <i>signum</i> function, which is defined to return one of <tt>-1</tt>,117* <tt>0</tt>, or <tt>1</tt> according to whether the value of118* <i>expression</i> is negative, zero or positive.<p>119*120* The implementor must ensure that <tt>sgn(compare(x, y)) ==121* -sgn(compare(y, x))</tt> for all <tt>x</tt> and <tt>y</tt>. (This122* implies that <tt>compare(x, y)</tt> must throw an exception if and only123* if <tt>compare(y, x)</tt> throws an exception.)<p>124*125* The implementor must also ensure that the relation is transitive:126* <tt>((compare(x, y)>0) && (compare(y, z)>0))</tt> implies127* <tt>compare(x, z)>0</tt>.<p>128*129* Finally, the implementor must ensure that <tt>compare(x, y)==0</tt>130* implies that <tt>sgn(compare(x, z))==sgn(compare(y, z))</tt> for all131* <tt>z</tt>.<p>132*133* It is generally the case, but <i>not</i> strictly required that134* <tt>(compare(x, y)==0) == (x.equals(y))</tt>. Generally speaking,135* any comparator that violates this condition should clearly indicate136* this fact. The recommended language is "Note: this comparator137* imposes orderings that are inconsistent with equals."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 the142* first argument is less than, equal to, or greater than the143* second.144* @throws NullPointerException if an argument is null and this145* comparator does not permit null arguments146* @throws ClassCastException if the arguments' types prevent them from147* being compared by this comparator.148*/149int compare(T o1, T o2);150151/**152* Indicates whether some other object is "equal to" this153* comparator. This method must obey the general contract of154* {@link Object#equals(Object)}. Additionally, this method can return155* <tt>true</tt> <i>only</i> if the specified object is also a comparator156* and it imposes the same ordering as this comparator. Thus,157* <code>comp1.equals(comp2)</code> implies that <tt>sgn(comp1.compare(o1,158* o2))==sgn(comp2.compare(o1, o2))</tt> for every object reference159* <tt>o1</tt> and <tt>o2</tt>.<p>160*161* Note that it is <i>always</i> safe <i>not</i> to override162* <tt>Object.equals(Object)</tt>. However, overriding this method may,163* in some cases, improve performance by allowing programs to determine164* that two distinct comparators impose the same order.165*166* @param obj the reference object with which to compare.167* @return <code>true</code> only if the specified object is also168* a comparator and it imposes the same ordering as this169* comparator.170* @see Object#equals(Object)171* @see Object#hashCode()172*/173boolean equals(Object obj);174175/**176* Returns a comparator that imposes the reverse ordering of this177* comparator.178*179* @return a comparator that imposes the reverse ordering of this180* comparator.181* @since 1.8182*/183default Comparator<T> reversed() {184return Collections.reverseOrder(this);185}186187/**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 comparator193* is also serializable.194*195* @apiNote196* For example, to sort a collection of {@code String} based on the length197* and then case-insensitive natural ordering, the comparator can be198* composed using following code,199*200* <pre>{@code201* 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 comparator206* compares two objects that are equal.207* @return a lexicographic-order comparator composed of this and then the208* other comparator209* @throws NullPointerException if the argument is null.210* @since 1.8211*/212default Comparator<T> thenComparing(Comparator<? super T> other) {213Objects.requireNonNull(other);214return (Comparator<T> & Serializable) (c1, c2) -> {215int res = compare(c1, c2);216return (res != 0) ? res : other.compare(c1, c2);217};218}219220/**221* Returns a lexicographic-order comparator with a function that222* extracts a key to be compared with the given {@code Comparator}.223*224* @implSpec This default implementation behaves as if {@code225* thenComparing(comparing(keyExtractor, cmp))}.226*227* @param <U> the type of the sort key228* @param keyExtractor the function used to extract the sort key229* @param keyComparator the {@code Comparator} used to compare the sort key230* @return a lexicographic-order comparator composed of this comparator231* and then comparing on the key extracted by the keyExtractor function232* @throws NullPointerException if either argument is null.233* @see #comparing(Function, Comparator)234* @see #thenComparing(Comparator)235* @since 1.8236*/237default <U> Comparator<T> thenComparing(238Function<? super T, ? extends U> keyExtractor,239Comparator<? super U> keyComparator)240{241return thenComparing(comparing(keyExtractor, keyComparator));242}243244/**245* Returns a lexicographic-order comparator with a function that246* extracts a {@code Comparable} sort key.247*248* @implSpec This default implementation behaves as if {@code249* thenComparing(comparing(keyExtractor))}.250*251* @param <U> the type of the {@link Comparable} sort key252* @param keyExtractor the function used to extract the {@link253* Comparable} sort key254* @return a lexicographic-order comparator composed of this and then the255* {@link Comparable} sort key.256* @throws NullPointerException if the argument is null.257* @see #comparing(Function)258* @see #thenComparing(Comparator)259* @since 1.8260*/261default <U extends Comparable<? super U>> Comparator<T> thenComparing(262Function<? super T, ? extends U> keyExtractor)263{264return thenComparing(comparing(keyExtractor));265}266267/**268* Returns a lexicographic-order comparator with a function that269* extracts a {@code int} sort key.270*271* @implSpec This default implementation behaves as if {@code272* thenComparing(comparingInt(keyExtractor))}.273*274* @param keyExtractor the function used to extract the integer sort key275* @return a lexicographic-order comparator composed of this and then the276* {@code int} sort key277* @throws NullPointerException if the argument is null.278* @see #comparingInt(ToIntFunction)279* @see #thenComparing(Comparator)280* @since 1.8281*/282default Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor) {283return thenComparing(comparingInt(keyExtractor));284}285286/**287* Returns a lexicographic-order comparator with a function that288* extracts a {@code long} sort key.289*290* @implSpec This default implementation behaves as if {@code291* thenComparing(comparingLong(keyExtractor))}.292*293* @param keyExtractor the function used to extract the long sort key294* @return a lexicographic-order comparator composed of this and then the295* {@code long} sort key296* @throws NullPointerException if the argument is null.297* @see #comparingLong(ToLongFunction)298* @see #thenComparing(Comparator)299* @since 1.8300*/301default Comparator<T> thenComparingLong(ToLongFunction<? super T> keyExtractor) {302return thenComparing(comparingLong(keyExtractor));303}304305/**306* Returns a lexicographic-order comparator with a function that307* extracts a {@code double} sort key.308*309* @implSpec This default implementation behaves as if {@code310* thenComparing(comparingDouble(keyExtractor))}.311*312* @param keyExtractor the function used to extract the double sort key313* @return a lexicographic-order comparator composed of this and then the314* {@code double} sort key315* @throws NullPointerException if the argument is null.316* @see #comparingDouble(ToDoubleFunction)317* @see #thenComparing(Comparator)318* @since 1.8319*/320default Comparator<T> thenComparingDouble(ToDoubleFunction<? super T> keyExtractor) {321return thenComparing(comparingDouble(keyExtractor));322}323324/**325* Returns a comparator that imposes the reverse of the <em>natural326* ordering</em>.327*328* <p>The returned comparator is serializable and throws {@link329* NullPointerException} when comparing {@code null}.330*331* @param <T> the {@link Comparable} type of element to be compared332* @return a comparator that imposes the reverse of the <i>natural333* ordering</i> on {@code Comparable} objects.334* @see Comparable335* @since 1.8336*/337public static <T extends Comparable<? super T>> Comparator<T> reverseOrder() {338return Collections.reverseOrder();339}340341/**342* Returns a comparator that compares {@link Comparable} objects in natural343* order.344*345* <p>The returned comparator is serializable and throws {@link346* NullPointerException} when comparing {@code null}.347*348* @param <T> the {@link Comparable} type of element to be compared349* @return a comparator that imposes the <i>natural ordering</i> on {@code350* Comparable} objects.351* @see Comparable352* @since 1.8353*/354@SuppressWarnings("unchecked")355public static <T extends Comparable<? super T>> Comparator<T> naturalOrder() {356return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE;357}358359/**360* Returns a null-friendly comparator that considers {@code null} to be361* less than non-null. When both are {@code null}, they are considered362* equal. If both are non-null, the specified {@code Comparator} is used363* 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 comparator367* is serializable.368*369* @param <T> the type of the elements to be compared370* @param comparator a {@code Comparator} for comparing non-null values371* @return a comparator that considers {@code null} to be less than372* non-null, and compares non-null objects with the supplied373* {@code Comparator}.374* @since 1.8375*/376public static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator) {377return new Comparators.NullComparator<>(true, comparator);378}379380/**381* Returns a null-friendly comparator that considers {@code null} to be382* greater than non-null. When both are {@code null}, they are considered383* equal. If both are non-null, the specified {@code Comparator} is used384* 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 comparator388* is serializable.389*390* @param <T> the type of the elements to be compared391* @param comparator a {@code Comparator} for comparing non-null values392* @return a comparator that considers {@code null} to be greater than393* non-null, and compares non-null objects with the supplied394* {@code Comparator}.395* @since 1.8396*/397public static <T> Comparator<T> nullsLast(Comparator<? super T> comparator) {398return new Comparators.NullComparator<>(false, comparator);399}400401/**402* Accepts a function that extracts a sort key from a type {@code T}, and403* returns a {@code Comparator<T>} that compares by that sort key using404* the specified {@link Comparator}.405*406* <p>The returned comparator is serializable if the specified function407* and comparator are both serializable.408*409* @apiNote410* For example, to obtain a {@code Comparator} that compares {@code411* Person} objects by their last name ignoring case differences,412*413* <pre>{@code414* 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 compared420* @param <U> the type of the sort key421* @param keyExtractor the function used to extract the sort key422* @param keyComparator the {@code Comparator} used to compare the sort key423* @return a comparator that compares by an extracted key using the424* specified {@code Comparator}425* @throws NullPointerException if either argument is null426* @since 1.8427*/428public static <T, U> Comparator<T> comparing(429Function<? super T, ? extends U> keyExtractor,430Comparator<? super U> keyComparator)431{432Objects.requireNonNull(keyExtractor);433Objects.requireNonNull(keyComparator);434return (Comparator<T> & Serializable)435(c1, c2) -> keyComparator.compare(keyExtractor.apply(c1),436keyExtractor.apply(c2));437}438439/**440* Accepts a function that extracts a {@link java.lang.Comparable441* Comparable} sort key from a type {@code T}, and returns a {@code442* Comparator<T>} that compares by that sort key.443*444* <p>The returned comparator is serializable if the specified function445* is also serializable.446*447* @apiNote448* For example, to obtain a {@code Comparator} that compares {@code449* Person} objects by their last name,450*451* <pre>{@code452* Comparator<Person> byLastName = Comparator.comparing(Person::getLastName);453* }</pre>454*455* @param <T> the type of element to be compared456* @param <U> the type of the {@code Comparable} sort key457* @param keyExtractor the function used to extract the {@link458* Comparable} sort key459* @return a comparator that compares by an extracted key460* @throws NullPointerException if the argument is null461* @since 1.8462*/463public static <T, U extends Comparable<? super U>> Comparator<T> comparing(464Function<? super T, ? extends U> keyExtractor)465{466Objects.requireNonNull(keyExtractor);467return (Comparator<T> & Serializable)468(c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));469}470471/**472* Accepts a function that extracts an {@code int} sort key from a type473* {@code T}, and returns a {@code Comparator<T>} that compares by that474* sort key.475*476* <p>The returned comparator is serializable if the specified function477* is also serializable.478*479* @param <T> the type of element to be compared480* @param keyExtractor the function used to extract the integer sort key481* @return a comparator that compares by an extracted key482* @see #comparing(Function)483* @throws NullPointerException if the argument is null484* @since 1.8485*/486public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) {487Objects.requireNonNull(keyExtractor);488return (Comparator<T> & Serializable)489(c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2));490}491492/**493* Accepts a function that extracts a {@code long} sort key from a type494* {@code T}, and returns a {@code Comparator<T>} that compares by that495* sort key.496*497* <p>The returned comparator is serializable if the specified function is498* also serializable.499*500* @param <T> the type of element to be compared501* @param keyExtractor the function used to extract the long sort key502* @return a comparator that compares by an extracted key503* @see #comparing(Function)504* @throws NullPointerException if the argument is null505* @since 1.8506*/507public static <T> Comparator<T> comparingLong(ToLongFunction<? super T> keyExtractor) {508Objects.requireNonNull(keyExtractor);509return (Comparator<T> & Serializable)510(c1, c2) -> Long.compare(keyExtractor.applyAsLong(c1), keyExtractor.applyAsLong(c2));511}512513/**514* Accepts a function that extracts a {@code double} sort key from a type515* {@code T}, and returns a {@code Comparator<T>} that compares by that516* sort key.517*518* <p>The returned comparator is serializable if the specified function519* is also serializable.520*521* @param <T> the type of element to be compared522* @param keyExtractor the function used to extract the double sort key523* @return a comparator that compares by an extracted key524* @see #comparing(Function)525* @throws NullPointerException if the argument is null526* @since 1.8527*/528public static<T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor) {529Objects.requireNonNull(keyExtractor);530return (Comparator<T> & Serializable)531(c1, c2) -> Double.compare(keyExtractor.applyAsDouble(c1), keyExtractor.applyAsDouble(c2));532}533}534535536