Java Comparator源码总结 Comparator源码注释翻译和解析中英文对照版

版本
JDK8(JDK1.8)

Comparator接口重点
1.Comparator接口是一个函数式接口,里面只有一个虚方法compare(T o1, T o2),该接口表示一个比较器,而实现Comparable接口则表示其实现类是可比较的,Comparable接口的虚方法是compareTo(T o)
Comparable接口源码可以看我这篇位置 Comparable

2.compare(T o1, T o2) 返回值大于0,表示 o1 - o2 > 0,若o1,o2相等,则compare(T o1, T o2) 返回0

3.Comparator接口方法
注:then开头比较器都是二次比较器,在第一次调用this.compare(T o1, T o2)两者相等,才会使用一个新的比较器来区分两者顺序,如果第一次都不相等,则不会调用后续比较器

方法名作用
int compare(T o1, T o2)返回 o1 - o2 的值
Comparator comparing(Function keyExtractor)返回一个新的比较器,其比较规则先经过keyExtractor处理o1和o2后,再将处理后的值相减c比较大小(类似相减,其实是调用compareTo)
Comparator comparing( Function keyExtractor, Comparator keyComparator)返回一个新的比较器,其比较规则先经过keyExtractor处理o1和o2后,再将使用keyComparator比较器的规则比较大小
Comparator comparingInt(ToIntFunction keyExtractor)和上面comparing(Function keyExtractor) 差不多,只不过ToIntFunction处理后得到的值是Int,则再两个Int相减
Comparator comparingLong(ToLongFunction keyExtractor)和上面comparing(Function keyExtractor) 差不多,只不过ToLongFunction处理后得到的值是Long,则再两个Long相减
Comparator comparingDouble(ToDoubleFunction keyExtractor)和上面comparing(Function keyExtractor) 差不多,只不过ToDoubleFunction处理后得到的值是Double,则再两个Double相减
Comparator naturalOrder()返回一个自然顺序比较器,比较规则为o1.compareTo(o2),相当于o1-o2
Comparator reverseOrder()返回一个与自然顺序比较器相反的比较器,比较规则为o2.compareTo(o1),相当于o2-o1
Comparato nullsFirst(Comparator comparator)返回一个空友好的比较器,该比较器认为null小于非空,两个null相等
Comparator nullsLast(Comparator comparator)返回一个空友好的比较器,该比较器认为null大于非空,两个null相等
Comparator reversed()返回一个新的比较器,它的compare(T o1, T o2) 的作用变成返回 o2 - o1 的值,即相反
Comparator thenComparing(Comparator other)返回一个新的比较器,当调用this.compare(T o1, T o2)时o1和o2相等,再调用other.compare(T o1, T o2)比较o1,o2,如果第一步不相等则直接返回,下面也一样
Comparator thenComparing(Function keyExtractor)当调用this.compare(T o1, T o2)时o1和o2相等,上面的other比较器用以下步骤生成的比较器替代,该比较器符合以下步骤,会先用keyExtractor处理o1,o2,然后直接把处理后的值相减
Comparator thenComparing(Function keyExtractor, Comparator keyComparator)当调用this.compare(T o1, T o2)时o1和o2相等,上面的other比较器用以下步骤生成的比较器替代,该比较器符合以下步骤,先用keyExtractor处理o1,o2,再调用keyComparator比较处理后的值
Comparator thenComparingInt(ToIntFunction keyExtractor)和上面 thenComparing(Function keyExtractor)差不多,只是 只不过ToIntFunction处理后得到的值是Int,然后两个Int相减
Comparator thenComparingLong(ToLongFunction keyExtractor)和上面 thenComparing(Function keyExtractor)差不多,只不过ToLongFunction处理后得到的值是Long,则再两个Long相减
Comparator thenComparingDouble(ToDoubleFunction keyExtractor)和上面 thenComparing(Function keyExtractor)差不多, 只不过ToDoubleFunction处理后得到的值是Double,则再两个Double相减

Comparator接口源码

package java.util;

import java.io.Serializable;
import java.util.function.Function;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import java.util.function.ToDoubleFunction;
import java.util.Comparators;

/**
 * A comparison function, which imposes a <i>total ordering</i> on some
 * collection of objects.  Comparators can be passed to a sort method (such
 * as {@link Collections#sort(List,Comparator) Collections.sort} or {@link
 * Arrays#sort(Object[],Comparator) Arrays.sort}) to allow precise control
 * over the sort order.  Comparators can also be used to control the order of
 * certain data structures (such as {@link SortedSet sorted sets} or {@link
 * SortedMap sorted maps}), or to provide an ordering for collections of
 * objects that don't have a {@link Comparable natural ordering}.<p>
 * 一种比较函数,它对某些对象集合施加总排序。
 * 可以将比较器传递给排序方法(例如Collections#sort(List,Comparator)或
 * Arrays#sort(Object[],Comparator)),以便精确控制排序顺序。
 * 比较器还可用于控制某些数据结构的顺序(如SortedSet或SortedMap),
 * 或为没有Comparable自然顺序的对象集合提供排序。
 *
 * The ordering imposed by a comparator {@code c} on a set of elements
 * {@code S} is said to be <i>consistent with equals</i> if and only if
 * {@code c.compare(e1, e2)==0} has the same boolean value as
 * {@code e1.equals(e2)} for every {@code e1} and {@code e2} in
 * {@code S}.<p>
 * 当且仅当c.compare(e1,e2)具有与e1和e2中的每一个e1和e2相同的布尔值时,
 * 比较器c对一组元素S施加的排序称为与等于一致。
 * 
 * 
 * 
 *
 * Caution should be exercised when using a comparator capable of imposing an
 * ordering inconsistent with equals to order a sorted set (or sorted map).
 * Suppose a sorted set (or sorted map) with an explicit comparator {@code c}
 * is used with elements (or keys) drawn from a set {@code S}.  If the
 * ordering imposed by {@code c} on {@code S} is inconsistent with equals,
 * the sorted set (or sorted map) will behave "strangely."  In particular the
 * sorted set (or sorted map) will violate the general contract for set (or
 * map), which is defined in terms of {@code equals}.<p>
 * 当使用比较器时,应谨慎使用,
 * 比较器能够对排序集(或排序映射)施加与等于不一致的排序。
 * 假设一个带有显式比较器c的排序集(或排序映射)与从集合S中提取的元素(或键)一起使用。
 * 如果c对S施加的排序与等于不一致,则排序集(或排序映射)的行为将“奇怪”。
 * 特别是排序集(或排序映射)将违反集合(或映射)的一般契约,
 * 该契约是根据equals定义的。
 * 
 * 
 * 
 * 
 *
 * For example, suppose one adds two elements {@code a} and {@code b} such that
 * {@code (a.equals(b) && c.compare(a, b) != 0)}
 * to an empty {@code TreeSet} with comparator {@code c}.
 * The second {@code add} operation will return
 * true (and the size of the tree set will increase) because {@code a} and
 * {@code b} are not equivalent from the tree set's perspective, even though
 * this is contrary to the specification of the
 * {@link Set#add Set.add} method.<p>
 * 例如,假设添加两个元素a和b,使得(a.equals(b) && c.compare(a, b) != 0)
 * 到带有比较器c的空TreeSet。第二个add操作将返回true(树集的大小将增加),
 * 因为从树集的角度来看a和b并不等价,即使这与set#add方法的规范相反。
 * 
 * 
 * 
 * 
 *
 * Note: It is generally a good idea for comparators to also implement
 * {@code java.io.Serializable}, as they may be used as ordering methods in
 * serializable data structures (like {@link TreeSet}, {@link TreeMap}).  In
 * order for the data structure to serialize successfully, the comparator (if
 * provided) must implement {@code Serializable}.<p>
 * 注意:比较器也实现java.io.Serializable通常是一个好主意,
 * 因为它们可以用作可序列化数据结构(如TreeSet、TreeMap)中的排序方法。
 * 为了成功序列化数据结构,比较器(如果提供)必须实现Serializable
 * 
 * 
 * 
 *
 * For the mathematically inclined, the <i>relation</i> that defines the
 * <i>imposed ordering</i> that a given comparator {@code c} imposes on a
 * given set of objects {@code S} is:
 * 对于数学上倾向的,定义给定比较器c对给定对象集S施加的强制顺序的关系为:
 * 
 * <pre>
 *       {(x, y) such that c.compare(x, y) <= 0}.
 * </pre> 
 * The <i>quotient</i> for this total order is:
 * 此总顺序的商为:
 * <pre>
 *       {(x, y) such that c.compare(x, y) == 0}.
 * </pre>
 *
 * It follows immediately from the contract for {@code compare} that the
 * quotient is an <i>equivalence relation</i> on {@code S}, and that the
 * imposed ordering is a <i>total order</i> on {@code S}.  When we say that
 * the ordering imposed by {@code c} on {@code S} is <i>consistent with
 * equals</i>, we mean that the quotient for the ordering is the equivalence
 * relation defined by the objects' {@link Object#equals(Object)
 * equals(Object)} method(s):
 * 紧接着从compare的契约可以看出,商是S上的等价关系,
 * 并且强加的顺序是S上的总顺序。当我们说c对S施加的排序与等于一致时,
 * 我们的意思是排序的商是由对象Object#equals(Object)方法定义的等价关系
 * 
 * 
 * 
 * <pre>
 *     {(x, y) such that x.equals(y)}. 
 * </pre>
 *
 * <p>Unlike {@code Comparable}, a comparator may optionally permit
 * comparison of null arguments, while maintaining the requirements for
 * an equivalence relation.
 * 与Comparable不同,比较器可以选择允许比较空参数,同时保持对等价关系的要求。
 *
 * <p>This interface is a member of the
 * <a href="{@docRoot}/java/util/package-summary.html#CollectionsFramework">
 * Java Collections Framework</a>.
 *
 * @param <T> the type of objects that may be compared by this comparator
 *
 * @author  Josh Bloch
 * @author  Neal Gafter
 * @see Comparable
 * @see java.io.Serializable
 * @since 1.2
 */
@FunctionalInterface
public interface Comparator<T> {
    /**
     * Compares its two arguments for order.  Returns a negative integer,
     * zero, or a positive integer as the first argument is less than, equal
     * to, or greater than the second.<p>
     * 比较其两个参数的顺序。返回负整数、零或正整数,
     * 因为第一个参数小于、等于或大于第二个参数。
     *
     * The implementor must ensure that {@code sgn(compare(x, y)) ==
     * -sgn(compare(y, x))} for all {@code x} and {@code y}.  (This
     * implies that {@code compare(x, y)} must throw an exception if and only
     * if {@code compare(y, x)} throws an exception.)<p>
     * 实现者必须确保所有x和y的sgn(compare(x, y)) ==-sgn(compare(y, x))。
     * (这意味着compare(x, y)必须在且仅在 compare(y, x)引发异常时引发异常。)
     *
     * The implementor must also ensure that the relation is transitive:
     * {@code ((compare(x, y)>0) && (compare(y, z)>0))} implies
     * {@code compare(x, z)>0}.<p>
     * 实现者还必须确保关系是可传递的:
     * ((compare(x, y)>0) && (compare(y, z)>0))意味着compare(x, z)>0
     * 
     * 
     * 
     *
     * Finally, the implementor must ensure that {@code compare(x, y)==0}
     * implies that {@code sgn(compare(x, z))==sgn(compare(y, z))} for all
     * {@code z}.<p>
     * 最后,实现者必须确保compare(x, y)==0意味着所有z的
     * sgn(compare(x, z))==sgn(compare(y, z))
     * 
     * 
     *
     * It is generally the case, but <i>not</i> strictly required that
     * {@code (compare(x, y)==0) == (x.equals(y))}.  Generally speaking,
     * any comparator that violates this condition should clearly indicate
     * this fact.  The recommended language is "Note: this comparator
     * imposes orderings that are inconsistent with equals."<p>
     * 通常是这样的,但不是严格要求(compare(x, y)==0) == (x.equals(y))。
     * 一般来说,任何违反这一条件的比较国都应明确指出这一事实。
     * 推荐的语言是“注意:这个比较器强加的顺序与equals不一致。”
     * 
     *
     * In the foregoing description, the notation
     * {@code sgn(}<i>expression</i>{@code )} designates the mathematical
     * <i>signum</i> function, which is defined to return one of {@code -1},
     * {@code 0}, or {@code 1} according to whether the value of
     * <i>expression</i> is negative, zero, or positive, respectively.
     * 在前面的描述中,符号sgn(expression)指定数学符号函数,
     * 该函数被定义为根据表达式的值是负、零还是正分别返回-1、0或1中的一个。
     *
     * @param o1 the first object to be compared. 第一个要比较的对象。
     * @param o2 the second object to be compared. 要比较的第二个对象。
     * @return a negative integer, zero, or a positive integer as the
     *         first argument is less than, equal to, or greater than the
     *         second. 作为第一个参数的负整数、零或正整数小于、等于或大于第二个参数。
     * @throws NullPointerException if an argument is null and this
     *         comparator does not permit null arguments
     * @throws ClassCastException if the arguments' types prevent them from
     *         being compared by this comparator. 如果参数的类型阻止此比较器对其进行比较。
     */
    int compare(T o1, T o2);

    /**
     * Indicates whether some other object is &quot;equal to&quot; this
     * comparator.  This method must obey the general contract of
     * {@link Object#equals(Object)}.  Additionally, this method can return
     * {@code true} <i>only</i> if the specified object is also a comparator
     * and it imposes the same ordering as this comparator.  Thus,
     * {@code comp1.equals(comp2)} implies that {@code sgn(comp1.compare(o1,
     * o2))==sgn(comp2.compare(o1, o2))} for every object reference
     * {@code o1} and {@code o2}.<p>
     * 指示其他对象是否等于此比较器。
     * 此方法必须遵守Object#equals(Object)的一般约定。
     * 此外,仅当指定的对象也是一个比较器并且它施加了与此比较器相同的顺序时,
     * 此方法才能返回true。因此,comp1.equals(comp2)意味着对于每个对象引用o1和o2都有
     * sgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2))
     * 。
     * 
     * 
     *
     * Note that it is <i>always</i> safe <i>not</i> to override
     * {@code Object.equals(Object)}.  However, overriding this method may,
     * in some cases, improve performance by allowing programs to determine
     * that two distinct comparators impose the same order.
     * 注意,不重写Object.equals(Object)总是安全的。
     * 但是,在某些情况下,
     * 重写此方法可以通过允许程序确定两个不同的比较器施加相同的顺序来提高性能。
     *
     * @param   obj   the reference object with which to compare.
     * @return  {@code true} only if the specified object is also
     *          a comparator and it imposes the same ordering as this
     *          comparator.
     * @see Object#equals(Object)
     * @see Object#hashCode()
     */
    boolean equals(Object obj);

    /**
     * Returns a comparator that imposes the reverse ordering of this
     * comparator.
     * 返回一个比较器,该比较器对该比较器进行反向排序。
     *
     * @return a comparator that imposes the reverse ordering of this
     *         comparator. 一种比较器,对该比较器进行反向排序
     * @since 1.8
     */
    default Comparator<T> reversed() {
        return Collections.reverseOrder(this);
    }

    /**
     * Returns a lexicographic-order comparator with another comparator.
     * If this {@code Comparator} considers two elements equal, i.e.
     * {@code compare(a, b) == 0}, {@code other} is used to determine the order.
     * 返回一个字典顺序比较器和另一个比较器。如果此Comparator认为两个元素相等,
     * 即compare(a, b) == 0,则使用other确定顺序。
     *
     * <p>The returned comparator is serializable if the specified comparator
     * is also serializable.
     * 如果指定的比较器也可序列化,则返回的比较器可序列化。
     *
     * @apiNote
     * For example, to sort a collection of {@code String} based on the length
     * and then case-insensitive natural ordering, the comparator can be
     * composed using following code,
     * 例如,要根据长度对String集合进行排序,
     * 然后进行不区分大小写的自然排序,可以使用以下代码组合比较器:,
     *
     * <pre>{@code
     *     Comparator<String> cmp = Comparator.comparingInt(String::length)
     *             .thenComparing(String.CASE_INSENSITIVE_ORDER);
     * }</pre>
     *
     * @param  other the other comparator to be used when this comparator
     *         compares two objects that are equal. 当此比较器比较两个相等的对象时要使用的另一个比较器。
     * @return a lexicographic-order comparator composed of this and then the
     *         other comparator 由这个比较器和另一个比较器组成的字典顺序比较器
     * @throws NullPointerException if the argument is null.
     * @since 1.8
     */
    default Comparator<T> thenComparing(Comparator<? super T> other) {
        Objects.requireNonNull(other);
        return (Comparator<T> & Serializable) (c1, c2) -> {
            int res = compare(c1, c2);
            return (res != 0) ? res : other.compare(c1, c2);
        };
    }

    /**
     * Returns a lexicographic-order comparator with a function that
     * extracts a key to be compared with the given {@code Comparator}.
     * 返回字典顺序比较器,该比较器具有一个函数,
     * 该函数提取要与给定comparator进行比较的键。
     *
     * @implSpec This default implementation behaves as if {@code
     *           thenComparing(comparing(keyExtractor, cmp))}.
     *           这个默认实现的行为就像thenComparing(comparing(keyExtractor, cmp))
     *
     * @param  <U>  the type of the sort key
     * @param  keyExtractor the function used to extract the sort key
     * @param  keyComparator the {@code Comparator} used to compare the sort key
     * @return a lexicographic-order comparator composed of this comparator
     *         and then comparing on the key extracted by the keyExtractor function
     *         一种字典顺序比较器,由该比较器组成,然后对keyExtractor函数提取的密钥进行比较
     * 
     * 
     * @throws NullPointerException if either argument is null. 如果任一参数为空。
     * @see #comparing(Function, Comparator)
     * @see #thenComparing(Comparator)
     * @since 1.8
     */
    default <U> Comparator<T> thenComparing(
            Function<? super T, ? extends U> keyExtractor,
            Comparator<? super U> keyComparator)
    {
        return thenComparing(comparing(keyExtractor, keyComparator));
    }

    /**
     * Returns a lexicographic-order comparator with a function that
     * extracts a {@code Comparable} sort key.
     * 返回一个字典顺序比较器,该比较器带有一个提取compariable排序键的函数。
     *
     * @implSpec This default implementation behaves as if {@code
     *           thenComparing(comparing(keyExtractor))}.
     *          此默认实现的行为就像thenComparing(comparing(keyExtractor))
     *
     * @param  <U>  the type of the {@link Comparable} sort key 可比较的排序键的类型
     * @param  keyExtractor the function used to extract the {@link
     *         Comparable} sort key 用于提取可比较排序键的函数
     * @return a lexicographic-order comparator composed of this and then the
     *         {@link Comparable} sort key. 
     *         一种字典顺序比较器,由这个键和Comparable排序键组成。
     * 
     * 
     * @throws NullPointerException if the argument is null.
     * @see #comparing(Function)
     * @see #thenComparing(Comparator)
     * @since 1.8
     */
    default <U extends Comparable<? super U>> Comparator<T> thenComparing(
            Function<? super T, ? extends U> keyExtractor)
    {
        return thenComparing(comparing(keyExtractor));
    }

    /**
     * Returns a lexicographic-order comparator with a function that
     * extracts an {@code int} sort key.
     * 返回字典顺序比较器,该比较器带有一个提取int排序键的函数。
     *
     * @implSpec This default implementation behaves as if {@code
     *           thenComparing(comparingInt(keyExtractor))}.
     *          这个默认实现的行为就像thenComparing(comparingInt(keyExtractor))
     *
     * @param  keyExtractor the function used to extract the integer sort key 用于提取整数排序键的函数
     * @return a lexicographic-order comparator composed of this and then the
     *         {@code int} sort key 一种字典顺序比较器,由这个键和int排序键组成
     * @throws NullPointerException if the argument is null.
     * @see #comparingInt(ToIntFunction)
     * @see #thenComparing(Comparator)
     * @since 1.8
     */
    default Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor) {
        return thenComparing(comparingInt(keyExtractor));
    }

    /**
     * Returns a lexicographic-order comparator with a function that
     * extracts a {@code long} sort key.
     * 返回字典顺序比较器,该比较器带有一个提取long排序键的函数。
     *
     * @implSpec This default implementation behaves as if {@code
     *           thenComparing(comparingLong(keyExtractor))}.
     *          这个默认实现的行为就像thenComparing(comparingLong(keyExtractor))
     *
     * @param  keyExtractor the function used to extract the long sort key 用于提取long排序键的函数
     * @return a lexicographic-order comparator composed of this and then the
     *         {@code long} sort key 一种字典顺序比较器,由这个键和long排序键组成
     * @throws NullPointerException if the argument is null.
     * @see #comparingLong(ToLongFunction)
     * @see #thenComparing(Comparator)
     * @since 1.8
     */
    default Comparator<T> thenComparingLong(ToLongFunction<? super T> keyExtractor) {
        return thenComparing(comparingLong(keyExtractor));
    }

    /**
     * Returns a lexicographic-order comparator with a function that
     * extracts a {@code double} sort key.
     * 返回字典顺序比较器,该比较器带有一个提取double排序键的函数。
     *
     * @implSpec This default implementation behaves as if {@code
     *           thenComparing(comparingDouble(keyExtractor))}.
     *           这个默认实现的行为就像thenComparing(comparingDouble(keyExtractor))
     * 
     *
     * @param  keyExtractor the function used to extract the double sort key 用于提取double排序键的函数
     * @return a lexicographic-order comparator composed of this and then the
     *         {@code double} sort key 一种字典顺序比较器,由这个键和double排序键组成
     * @throws NullPointerException if the argument is null.
     * @see #comparingDouble(ToDoubleFunction)
     * @see #thenComparing(Comparator)
     * @since 1.8
     */
    default Comparator<T> thenComparingDouble(ToDoubleFunction<? super T> keyExtractor) {
        return thenComparing(comparingDouble(keyExtractor));
    }

    /**
     * Returns a comparator that imposes the reverse of the <em>natural
     * ordering</em>.
     * 返回与自然顺序相反的比较器
     *
     * <p>The returned comparator is serializable and throws {@link
     * NullPointerException} when comparing {@code null}.
     * 返回的比较器可序列化,并在比较null时抛出NullPointerException
     *
     * @param  <T> the {@link Comparable} type of element to be compared 待比较元素的可比较类型
     * @return a comparator that imposes the reverse of the <i>natural
     *         ordering</i> on {@code Comparable} objects.
     * @see Comparable
     * @since 1.8
     */
    public static <T extends Comparable<? super T>> Comparator<T> reverseOrder() {
        return Collections.reverseOrder();
    }

    /**
     * Returns a comparator that compares {@link Comparable} objects in natural
     * order.
     * 返回按自然顺序比较Comparable对象的比较器。
     *
     * <p>The returned comparator is serializable and throws {@link
     * NullPointerException} when comparing {@code null}.
     * 返回的比较器可序列化,并在比较null时抛出NullPointerException
     *
     * @param  <T> the {@link Comparable} type of element to be compared 要比较的元素的Comparable类型
     * @return a comparator that imposes the <i>natural ordering</i> on {@code
     *         Comparable} objects. 对compariable对象施加自然排序的比较器。
     * @see Comparable
     * @since 1.8
     */
    @SuppressWarnings("unchecked")
    public static <T extends Comparable<? super T>> Comparator<T> naturalOrder() {
        return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE;
    }

    /**
     * Returns a null-friendly comparator that considers {@code null} to be
     * less than non-null. When both are {@code null}, they are considered
     * equal. If both are non-null, the specified {@code Comparator} is used
     * to determine the order. If the specified comparator is {@code null},
     * then the returned comparator considers all non-null values to be equal.
     * 返回一个空友好的比较器,该比较器认为null小于非空。
     * 当两者都是null时,它们被视为相等。
     * 如果两者都非空,则使用指定的Comparator确定顺序。
     * 如果指定的比较器为null,则返回的比较器将认为所有非null值相等。
     *
     * <p>The returned comparator is serializable if the specified comparator
     * is serializable.
     * 如果指定的比较器可序列化,则返回的比较器可序列化。
     *
     * @param  <T> the type of the elements to be compared
     * @param  comparator a {@code Comparator} for comparing non-null values
     * @return a comparator that considers {@code null} to be less than
     *         non-null, and compares non-null objects with the supplied
     *         {@code Comparator}.
     *         一种比较器,它认为null小于非null,并将非null对象与提供的comparator进行比较。
     * @since 1.8
     */
    public static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator) {
        return new Comparators.NullComparator<>(true, comparator);
    }

    /**
     * Returns a null-friendly comparator that considers {@code null} to be
     * greater than non-null. When both are {@code null}, they are considered
     * equal. If both are non-null, the specified {@code Comparator} is used
     * to determine the order. If the specified comparator is {@code null},
     * then the returned comparator considers all non-null values to be equal.
     * 返回一个空友好的比较器,该比较器认为null大于非空。
     * 当两者都是null时,它们被视为相等。如果两者都非空,
     * 则使用指定的Comparator确定顺序。如果指定的比较器为null,
     * 则返回的比较器将认为所有非null值相等。
     *
     * <p>The returned comparator is serializable if the specified comparator
     * is serializable.
     * 如果指定的比较器可序列化,则返回的比较器可序列化。
     *
     * @param  <T> the type of the elements to be compared
     * @param  comparator a {@code Comparator} for comparing non-null values
     * @return a comparator that considers {@code null} to be greater than
     *         non-null, and compares non-null objects with the supplied
     *         {@code Comparator}.
     *         一种比较器,它认为null大于非null,
     *         并将非null对象与提供的 comparator 进行比较。
     * 
     * @since 1.8
     */
    public static <T> Comparator<T> nullsLast(Comparator<? super T> comparator) {
        return new Comparators.NullComparator<>(false, comparator);
    }

    /**
     * Accepts a function that extracts a sort key from a type {@code T}, and
     * returns a {@code Comparator<T>} that compares by that sort key using
     * the specified {@link Comparator}.
     * 接受一个函数,该函数从类型T中提取排序键,
     * 并返回一个Comparator<T>,使用指定的Comparator按该排序键进行比较。
     *
     * <p>The returned comparator is serializable if the specified function
     * and comparator are both serializable.
     * 如果指定的函数和比较器都可序列化,则返回的比较器可序列化。
     *
     * @apiNote
     * For example, to obtain a {@code Comparator} that compares {@code
     * Person} objects by their last name ignoring case differences,
     * 例如,要获得一个Comparator,
     * 它根据Person对象的姓氏比较Person对象,忽略大小写差异,
     *
     * <pre>{@code
     *     Comparator<Person> cmp = Comparator.comparing(
     *             Person::getLastName,
     *             String.CASE_INSENSITIVE_ORDER);
     * }</pre>
     *
     * @param  <T> the type of element to be compared
     * @param  <U> the type of the sort key
     * @param  keyExtractor the function used to extract the sort key 用于提取排序键的函数
     * @param  keyComparator the {@code Comparator} used to compare the sort key 用于比较排序键的Comparator
     * @return a comparator that compares by an extracted key using the
     *         specified {@code Comparator} 一种比较器,使用指定的comparator通过提取的键进行比较
     * @throws NullPointerException if either argument is null
     * @since 1.8
     */
    public static <T, U> Comparator<T> comparing(
            Function<? super T, ? extends U> keyExtractor,
            Comparator<? super U> keyComparator)
    {
        Objects.requireNonNull(keyExtractor);
        Objects.requireNonNull(keyComparator);
        return (Comparator<T> & Serializable)
            (c1, c2) -> keyComparator.compare(keyExtractor.apply(c1),
                                              keyExtractor.apply(c2));
    }

    /**
     * Accepts a function that extracts a {@link java.lang.Comparable
     * Comparable} sort key from a type {@code T}, and returns a {@code
     * Comparator<T>} that compares by that sort key.
     * 接受一个函数,该函数从类型T中提取java.lang.Comparable排序键,
     * 并返回一个Comparator<T>按该排序键进行比较。
     *
     * <p>The returned comparator is serializable if the specified function
     * is also serializable.
     * 如果指定的函数也可序列化,则返回的比较器可序列化。
     *
     * @apiNote
     * For example, to obtain a {@code Comparator} that compares {@code
     * Person} objects by their last name,
     * 例如,要获得一个Comparator,它根据Person对象的姓氏对其进行比较,
     *
     * <pre>{@code
     *     Comparator<Person> byLastName = Comparator.comparing(Person::getLastName);
     * }</pre>
     *
     * @param  <T> the type of element to be compared
     * @param  <U> the type of the {@code Comparable} sort key
     * @param  keyExtractor the function used to extract the {@link
     *         Comparable} sort key
     * @return a comparator that compares by an extracted key
     * @throws NullPointerException if the argument is null
     * @since 1.8
     */
    public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
            Function<? super T, ? extends U> keyExtractor)
    {
        Objects.requireNonNull(keyExtractor);
        return (Comparator<T> & Serializable)
            (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
    }

    /**
     * Accepts a function that extracts an {@code int} sort key from a type
     * {@code T}, and returns a {@code Comparator<T>} that compares by that
     * sort key.
     * 接受一个函数,该函数从类型T中提取int排序键,
     * 并返回一个Comparator<T>以该排序键进行比较。
     *
     * <p>The returned comparator is serializable if the specified function
     * is also serializable.
     * 如果指定的函数也可序列化,则返回的比较器可序列化。
     *
     * @param  <T> the type of element to be compared 要比较的元素的类型
     * @param  keyExtractor the function used to extract the integer sort key 用于提取整数排序键的函数
     * @return a comparator that compares by an extracted key 通过提取的键进行比较的比较器
     * @see #comparing(Function)
     * @throws NullPointerException if the argument is null
     * @since 1.8
     */
    public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) {
        Objects.requireNonNull(keyExtractor);
        return (Comparator<T> & Serializable)
            (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2));
    }

    /**
     * Accepts a function that extracts a {@code long} sort key from a type
     * {@code T}, and returns a {@code Comparator<T>} that compares by that
     * sort key.
     * 接受一个函数,该函数从类型T中提取long排序键,
     * 并返回一个Comparator<T>以该排序键进行比较。
     *
     * <p>The returned comparator is serializable if the specified function is
     * also serializable.
     * 如果指定的函数也可序列化,则返回的比较器可序列化。
     *
     * @param  <T> the type of element to be compared 要比较的元素的类型
     * @param  keyExtractor the function used to extract the long sort key 用于提取长排序键的函数
     * @return a comparator that compares by an extracted key 通过提取的键进行比较的比较器
     * @see #comparing(Function)
     * @throws NullPointerException if the argument is null
     * @since 1.8
     */
    public static <T> Comparator<T> comparingLong(ToLongFunction<? super T> keyExtractor) {
        Objects.requireNonNull(keyExtractor);
        return (Comparator<T> & Serializable)
            (c1, c2) -> Long.compare(keyExtractor.applyAsLong(c1), keyExtractor.applyAsLong(c2));
    }

    /**
     * Accepts a function that extracts a {@code double} sort key from a type
     * {@code T}, and returns a {@code Comparator<T>} that compares by that
     * sort key.
     * 接受一个函数,该函数从类型T中提取double排序键,
     * 并返回一个Comparator<T>以该排序键进行比较。
     *
     * <p>The returned comparator is serializable if the specified function
     * is also serializable.
     * 如果指定的函数也可序列化,则返回的比较器可序列化。
     *
     * @param  <T> the type of element to be compared
     * @param  keyExtractor the function used to extract the double sort key
     * @return a comparator that compares by an extracted key
     * @see #comparing(Function)
     * @throws NullPointerException if the argument is null
     * @since 1.8
     */
    public static<T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor) {
        Objects.requireNonNull(keyExtractor);
        return (Comparator<T> & Serializable)
            (c1, c2) -> Double.compare(keyExtractor.applyAsDouble(c1), keyExtractor.applyAsDouble(c2));
    }
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java中,Comparator接口用于定义两个对象的比较方式。Comparator接口中只有一个方法,即compare(Object o1, Object o2),该方法返回一个int类型值,表示两个对象之间的大小关系。 在Java中,我们可以使用Comparator接口对集合中的元素进行排序。具体来说,我们可以使用Collections.sort()方法对List进行排序,该方法接收一个Comparator类型的参数来指定排序的方式。 Comparator接口中的compare方法的返回值代表了两个对象之间的大小关系。当compare方法返回负数时,表示o1小于o2;当compare方法返回正数时,表示o1大于o2;当compare方法返回0时,表示o1等于o2。 下面是一个使用Comparator接口对List进行排序的例子: ``` List<Integer> list = new ArrayList<>(); list.add(3); list.add(1); list.add(2); Collections.sort(list, new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o1 - o2; } }); ``` 在这个例子中,我们创建了一个包含三个整数的List,并使用Collections.sort()方法对其进行排序。我们使用了一个匿名内部类来实现Comparator接口,将整数按升序排序。 在Java中,Comparator接口的实现方式有很多种,例如可以使用Lambda表达式、Comparator.comparing()方法、Comparator.thenComparing()方法等。这些方法都可以帮助我们更方便地实现Comparator接口。 总之,Comparator接口是Java中非常重要的一个接口,它提供了一种灵活的方法来对集合中的元素进行排序。熟练掌握Comparator接口的使用方法可以让我们更好地处理集合数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lolxxs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值