Path: blob/master/src/java.base/share/classes/java/util/Comparator.java
41152 views
/*1* Copyright (c) 1997, 2021, 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> on36* some collection of objects. Comparators can be passed to a sort37* method (such as {@link Collections#sort(List,Comparator)38* Collections.sort} or {@link Arrays#sort(Object[],Comparator)39* Arrays.sort}) to allow precise control over the sort order.40* Comparators can also be used to control the order of certain data41* structures (such as {@linkplain SortedSet sorted sets} or42* {@linkplain SortedMap sorted maps}), or to provide an ordering for43* collections of objects that don't have a {@linkplain Comparable44* natural ordering}.<p>45*46* The ordering imposed by a comparator {@code c} on a set of elements47* {@code S} is said to be <i>consistent with equals</i> if and only if48* {@code c.compare(e1, e2)==0} has the same boolean value as49* {@code e1.equals(e2)} for every {@code e1} and {@code e2} in50* {@code S}.<p>51*52* Caution should be exercised when using a comparator capable of imposing an53* ordering inconsistent with equals to order a sorted set (or sorted map).54* Suppose a sorted set (or sorted map) with an explicit comparator {@code c}55* is used with elements (or keys) drawn from a set {@code S}. If the56* ordering imposed by {@code c} on {@code S} is inconsistent with equals,57* the sorted set (or sorted map) will behave "strangely." In particular the58* sorted set (or sorted map) will violate the general contract for set (or59* map), which is defined in terms of {@code equals}.<p>60*61* For example, suppose one adds two elements {@code a} and {@code b} such that62* {@code (a.equals(b) && c.compare(a, b) != 0)}63* to an empty {@code TreeSet} with comparator {@code c}.64* The second {@code add} operation will return65* true (and the size of the tree set will increase) because {@code a} and66* {@code b} are not equivalent from the tree set's perspective, even though67* this is contrary to the specification of the68* {@link Set#add Set.add} method.<p>69*70* Note: It is generally a good idea for comparators to also implement71* {@code java.io.Serializable}, as they may be used as ordering methods in72* serializable data structures (like {@link TreeSet}, {@link TreeMap}). In73* order for the data structure to serialize successfully, the comparator (if74* provided) must implement {@code Serializable}.<p>75*76* For the mathematically inclined, the <i>relation</i> that defines the77* <i>imposed ordering</i> that a given comparator {@code c} imposes on a78* given set of objects {@code S} is:<pre>79* {(x, y) such that c.compare(x, y) <= 0}.80* </pre> The <i>quotient</i> for this total order is:<pre>81* {(x, y) such that c.compare(x, y) == 0}.82* </pre>83*84* It follows immediately from the contract for {@code compare} that the85* quotient is an <i>equivalence relation</i> on {@code S}, and that the86* imposed ordering is a <i>total order</i> on {@code S}. When we say that87* the ordering imposed by {@code c} on {@code S} is <i>consistent with88* equals</i>, we mean that the quotient for the ordering is the equivalence89* relation defined by the objects' {@link Object#equals(Object)90* equals(Object)} method(s):<pre>91* {(x, y) such that x.equals(y)}. </pre>92*93* In other words, when the imposed ordering is consistent with94* equals, the equivalence classes defined by the equivalence relation95* of the {@code equals} method and the equivalence classes defined by96* the quotient of the {@code compare} method are the same.9798* <p>Unlike {@code Comparable}, a comparator may optionally permit99* comparison of null arguments, while maintaining the requirements for100* an equivalence relation.101*102* <p>This interface is a member of the103* <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">104* Java Collections Framework</a>.105*106* @param <T> the type of objects that may be compared by this comparator107*108* @author Josh Bloch109* @author Neal Gafter110* @see Comparable111* @see java.io.Serializable112* @since 1.2113*/114@FunctionalInterface115public interface Comparator<T> {116/**117* Compares its two arguments for order. Returns a negative integer,118* zero, or a positive integer as the first argument is less than, equal119* to, or greater than the second.<p>120*121* The implementor must ensure that {@link Integer#signum122* signum}{@code (compare(x, y)) == -signum(compare(y, x))} for123* all {@code x} and {@code y}. (This implies that {@code124* compare(x, y)} must throw an exception if and only if {@code125* compare(y, x)} throws an exception.)<p>126*127* The implementor must also ensure that the relation is transitive:128* {@code ((compare(x, y)>0) && (compare(y, z)>0))} implies129* {@code compare(x, z)>0}.<p>130*131* Finally, the implementor must ensure that {@code compare(x,132* y)==0} implies that {@code signum(compare(x,133* z))==signum(compare(y, z))} for all {@code z}.134*135* @apiNote136* It is generally the case, but <i>not</i> strictly required that137* {@code (compare(x, y)==0) == (x.equals(y))}. Generally speaking,138* any comparator that violates this condition should clearly indicate139* this fact. The recommended language is "Note: this comparator140* imposes orderings that are inconsistent with equals."141*142* @param o1 the first object to be compared.143* @param o2 the second object to be compared.144* @return a negative integer, zero, or a positive integer as the145* first argument is less than, equal to, or greater than the146* second.147* @throws NullPointerException if an argument is null and this148* comparator does not permit null arguments149* @throws ClassCastException if the arguments' types prevent them from150* being compared by this comparator.151*/152int compare(T o1, T o2);153154/**155* Indicates whether some other object is "equal to"156* this comparator. This method must obey the general contract of157* {@link Object#equals(Object)}. Additionally, this method can158* return {@code true} <i>only</i> if the specified object is also159* a comparator and it imposes the same ordering as this160* comparator. Thus, {@code comp1.equals(comp2)} implies that161* {@link Integer#signum signum}{@code (comp1.compare(o1,162* o2))==signum(comp2.compare(o1, o2))} for every object reference163* {@code o1} and {@code o2}.<p>164*165* Note that it is <i>always</i> safe <i>not</i> to override166* {@code Object.equals(Object)}. However, overriding this method may,167* in some cases, improve performance by allowing programs to determine168* that two distinct comparators impose the same order.169*170* @param obj the reference object with which to compare.171* @return {@code true} only if the specified object is also172* a comparator and it imposes the same ordering as this173* comparator.174* @see Object#equals(Object)175* @see Object#hashCode()176*/177boolean equals(Object obj);178179/**180* Returns a comparator that imposes the reverse ordering of this181* comparator.182*183* @return a comparator that imposes the reverse ordering of this184* comparator.185* @since 1.8186*/187default Comparator<T> reversed() {188return Collections.reverseOrder(this);189}190191/**192* Returns a lexicographic-order comparator with another comparator.193* If this {@code Comparator} considers two elements equal, i.e.194* {@code compare(a, b) == 0}, {@code other} is used to determine the order.195*196* <p>The returned comparator is serializable if the specified comparator197* is also serializable.198*199* @apiNote200* For example, to sort a collection of {@code String} based on the length201* and then case-insensitive natural ordering, the comparator can be202* composed using following code,203*204* <pre>{@code205* Comparator<String> cmp = Comparator.comparingInt(String::length)206* .thenComparing(String.CASE_INSENSITIVE_ORDER);207* }</pre>208*209* @param other the other comparator to be used when this comparator210* compares two objects that are equal.211* @return a lexicographic-order comparator composed of this and then the212* other comparator213* @throws NullPointerException if the argument is null.214* @since 1.8215*/216default Comparator<T> thenComparing(Comparator<? super T> other) {217Objects.requireNonNull(other);218return (Comparator<T> & Serializable) (c1, c2) -> {219int res = compare(c1, c2);220return (res != 0) ? res : other.compare(c1, c2);221};222}223224/**225* Returns a lexicographic-order comparator with a function that226* extracts a key to be compared with the given {@code Comparator}.227*228* @implSpec This default implementation behaves as if {@code229* thenComparing(comparing(keyExtractor, cmp))}.230*231* @param <U> the type of the sort key232* @param keyExtractor the function used to extract the sort key233* @param keyComparator the {@code Comparator} used to compare the sort key234* @return a lexicographic-order comparator composed of this comparator235* and then comparing on the key extracted by the keyExtractor function236* @throws NullPointerException if either argument is null.237* @see #comparing(Function, Comparator)238* @see #thenComparing(Comparator)239* @since 1.8240*/241default <U> Comparator<T> thenComparing(242Function<? super T, ? extends U> keyExtractor,243Comparator<? super U> keyComparator)244{245return thenComparing(comparing(keyExtractor, keyComparator));246}247248/**249* Returns a lexicographic-order comparator with a function that250* extracts a {@code Comparable} sort key.251*252* @implSpec This default implementation behaves as if {@code253* thenComparing(comparing(keyExtractor))}.254*255* @param <U> the type of the {@link Comparable} sort key256* @param keyExtractor the function used to extract the {@link257* Comparable} sort key258* @return a lexicographic-order comparator composed of this and then the259* {@link Comparable} sort key.260* @throws NullPointerException if the argument is null.261* @see #comparing(Function)262* @see #thenComparing(Comparator)263* @since 1.8264*/265default <U extends Comparable<? super U>> Comparator<T> thenComparing(266Function<? super T, ? extends U> keyExtractor)267{268return thenComparing(comparing(keyExtractor));269}270271/**272* Returns a lexicographic-order comparator with a function that273* extracts an {@code int} sort key.274*275* @implSpec This default implementation behaves as if {@code276* thenComparing(comparingInt(keyExtractor))}.277*278* @param keyExtractor the function used to extract the integer sort key279* @return a lexicographic-order comparator composed of this and then the280* {@code int} sort key281* @throws NullPointerException if the argument is null.282* @see #comparingInt(ToIntFunction)283* @see #thenComparing(Comparator)284* @since 1.8285*/286default Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor) {287return thenComparing(comparingInt(keyExtractor));288}289290/**291* Returns a lexicographic-order comparator with a function that292* extracts a {@code long} sort key.293*294* @implSpec This default implementation behaves as if {@code295* thenComparing(comparingLong(keyExtractor))}.296*297* @param keyExtractor the function used to extract the long sort key298* @return a lexicographic-order comparator composed of this and then the299* {@code long} sort key300* @throws NullPointerException if the argument is null.301* @see #comparingLong(ToLongFunction)302* @see #thenComparing(Comparator)303* @since 1.8304*/305default Comparator<T> thenComparingLong(ToLongFunction<? super T> keyExtractor) {306return thenComparing(comparingLong(keyExtractor));307}308309/**310* Returns a lexicographic-order comparator with a function that311* extracts a {@code double} sort key.312*313* @implSpec This default implementation behaves as if {@code314* thenComparing(comparingDouble(keyExtractor))}.315*316* @param keyExtractor the function used to extract the double sort key317* @return a lexicographic-order comparator composed of this and then the318* {@code double} sort key319* @throws NullPointerException if the argument is null.320* @see #comparingDouble(ToDoubleFunction)321* @see #thenComparing(Comparator)322* @since 1.8323*/324default Comparator<T> thenComparingDouble(ToDoubleFunction<? super T> keyExtractor) {325return thenComparing(comparingDouble(keyExtractor));326}327328/**329* Returns a comparator that imposes the reverse of the <em>natural330* ordering</em>.331*332* <p>The returned comparator is serializable and throws {@link333* NullPointerException} when comparing {@code null}.334*335* @param <T> the {@link Comparable} type of element to be compared336* @return a comparator that imposes the reverse of the <i>natural337* ordering</i> on {@code Comparable} objects.338* @see Comparable339* @since 1.8340*/341public static <T extends Comparable<? super T>> Comparator<T> reverseOrder() {342return Collections.reverseOrder();343}344345/**346* Returns a comparator that compares {@link Comparable} objects in natural347* order.348*349* <p>The returned comparator is serializable and throws {@link350* NullPointerException} when comparing {@code null}.351*352* @param <T> the {@link Comparable} type of element to be compared353* @return a comparator that imposes the <i>natural ordering</i> on {@code354* Comparable} objects.355* @see Comparable356* @since 1.8357*/358@SuppressWarnings("unchecked")359public static <T extends Comparable<? super T>> Comparator<T> naturalOrder() {360return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE;361}362363/**364* Returns a null-friendly comparator that considers {@code null} to be365* less than non-null. When both are {@code null}, they are considered366* equal. If both are non-null, the specified {@code Comparator} is used367* to determine the order. If the specified comparator is {@code null},368* then the returned comparator considers all non-null values to be equal.369*370* <p>The returned comparator is serializable if the specified comparator371* is serializable.372*373* @param <T> the type of the elements to be compared374* @param comparator a {@code Comparator} for comparing non-null values375* @return a comparator that considers {@code null} to be less than376* non-null, and compares non-null objects with the supplied377* {@code Comparator}.378* @since 1.8379*/380public static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator) {381return new Comparators.NullComparator<>(true, comparator);382}383384/**385* Returns a null-friendly comparator that considers {@code null} to be386* greater than non-null. When both are {@code null}, they are considered387* equal. If both are non-null, the specified {@code Comparator} is used388* to determine the order. If the specified comparator is {@code null},389* then the returned comparator considers all non-null values to be equal.390*391* <p>The returned comparator is serializable if the specified comparator392* is serializable.393*394* @param <T> the type of the elements to be compared395* @param comparator a {@code Comparator} for comparing non-null values396* @return a comparator that considers {@code null} to be greater than397* non-null, and compares non-null objects with the supplied398* {@code Comparator}.399* @since 1.8400*/401public static <T> Comparator<T> nullsLast(Comparator<? super T> comparator) {402return new Comparators.NullComparator<>(false, comparator);403}404405/**406* Accepts a function that extracts a sort key from a type {@code T}, and407* returns a {@code Comparator<T>} that compares by that sort key using408* the specified {@link Comparator}.409*410* <p>The returned comparator is serializable if the specified function411* and comparator are both serializable.412*413* @apiNote414* For example, to obtain a {@code Comparator} that compares {@code415* Person} objects by their last name ignoring case differences,416*417* <pre>{@code418* Comparator<Person> cmp = Comparator.comparing(419* Person::getLastName,420* String.CASE_INSENSITIVE_ORDER);421* }</pre>422*423* @param <T> the type of element to be compared424* @param <U> the type of the sort key425* @param keyExtractor the function used to extract the sort key426* @param keyComparator the {@code Comparator} used to compare the sort key427* @return a comparator that compares by an extracted key using the428* specified {@code Comparator}429* @throws NullPointerException if either argument is null430* @since 1.8431*/432public static <T, U> Comparator<T> comparing(433Function<? super T, ? extends U> keyExtractor,434Comparator<? super U> keyComparator)435{436Objects.requireNonNull(keyExtractor);437Objects.requireNonNull(keyComparator);438return (Comparator<T> & Serializable)439(c1, c2) -> keyComparator.compare(keyExtractor.apply(c1),440keyExtractor.apply(c2));441}442443/**444* Accepts a function that extracts a {@link java.lang.Comparable445* Comparable} sort key from a type {@code T}, and returns a {@code446* Comparator<T>} that compares by that sort key.447*448* <p>The returned comparator is serializable if the specified function449* is also serializable.450*451* @apiNote452* For example, to obtain a {@code Comparator} that compares {@code453* Person} objects by their last name,454*455* <pre>{@code456* Comparator<Person> byLastName = Comparator.comparing(Person::getLastName);457* }</pre>458*459* @param <T> the type of element to be compared460* @param <U> the type of the {@code Comparable} sort key461* @param keyExtractor the function used to extract the {@link462* Comparable} sort key463* @return a comparator that compares by an extracted key464* @throws NullPointerException if the argument is null465* @since 1.8466*/467public static <T, U extends Comparable<? super U>> Comparator<T> comparing(468Function<? super T, ? extends U> keyExtractor)469{470Objects.requireNonNull(keyExtractor);471return (Comparator<T> & Serializable)472(c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));473}474475/**476* Accepts a function that extracts an {@code int} sort key from a type477* {@code T}, and returns a {@code Comparator<T>} that compares by that478* sort key.479*480* <p>The returned comparator is serializable if the specified function481* is also serializable.482*483* @param <T> the type of element to be compared484* @param keyExtractor the function used to extract the integer sort key485* @return a comparator that compares by an extracted key486* @see #comparing(Function)487* @throws NullPointerException if the argument is null488* @since 1.8489*/490public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) {491Objects.requireNonNull(keyExtractor);492return (Comparator<T> & Serializable)493(c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2));494}495496/**497* Accepts a function that extracts a {@code long} sort key from a type498* {@code T}, and returns a {@code Comparator<T>} that compares by that499* sort key.500*501* <p>The returned comparator is serializable if the specified function is502* also serializable.503*504* @param <T> the type of element to be compared505* @param keyExtractor the function used to extract the long sort key506* @return a comparator that compares by an extracted key507* @see #comparing(Function)508* @throws NullPointerException if the argument is null509* @since 1.8510*/511public static <T> Comparator<T> comparingLong(ToLongFunction<? super T> keyExtractor) {512Objects.requireNonNull(keyExtractor);513return (Comparator<T> & Serializable)514(c1, c2) -> Long.compare(keyExtractor.applyAsLong(c1), keyExtractor.applyAsLong(c2));515}516517/**518* Accepts a function that extracts a {@code double} sort key from a type519* {@code T}, and returns a {@code Comparator<T>} that compares by that520* sort key.521*522* <p>The returned comparator is serializable if the specified function523* is also serializable.524*525* @param <T> the type of element to be compared526* @param keyExtractor the function used to extract the double sort key527* @return a comparator that compares by an extracted key528* @see #comparing(Function)529* @throws NullPointerException if the argument is null530* @since 1.8531*/532public static<T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor) {533Objects.requireNonNull(keyExtractor);534return (Comparator<T> & Serializable)535(c1, c2) -> Double.compare(keyExtractor.applyAsDouble(c1), keyExtractor.applyAsDouble(c2));536}537}538539540