Comparator比较不链

Comparator比较不链

本文介绍了Java 8 Comparator比较不链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个Pair类

Let's say I have a Pair class

public class Pair<P, Q> {
    public P p;
    public Q q;


    public Pair(P p, Q q) {
        this.p = p;
        this.q = q;
    }

    public int firstValue() {
        return ((Number)p).intValue();
    }

    public int secondValue() {
        return ((Number)q).intValue();
    }
}

我希望先按值排序,然后是第二个值。现在'如果我这样做'

And I wish to sort it, first by first value, then by second value. Now' if I do this

List<Pair<Integer, Integer>> pairList = new ArrayList<>();
pairList.add(new Pair<>(1, 5));
pairList.add(new Pair<>(2, 2));
pairList.add(new Pair<>(2, 22));
pairList.add(new Pair<>(1, 22));
pairList.sort(Comparator.comparing(Pair::firstValue));

一切运作良好,列表按对的第一个值排序,但如果我这样做

Everything works well and good, the list is sorted by first values of pair, but if I do this

pairList.sort(Comparator.comparing(Pair::firstValue).thenComparing(Pair::secondValue));

失败并出现错误

Error:(24, 38) java: incompatible types: cannot infer type-variable(s) T,U
(argument mismatch; invalid method reference
  method firstValue in class DataStructures.Pair<P,Q> cannot be applied to given types
    required: no arguments
    found: java.lang.Object
    reason: actual and formal argument lists differ in length)

好的,所以它可能无法推断出参数,所以如果我这样做

Ok,so it might not be able to infer the arguments, so if I do this

pairList.sort(Comparator.<Integer, Integer>comparing(Pair::firstValue)
                                          .thenComparing(Pair::secondValue));

失败并出现错误

Error:(24, 39) java: invalid method reference
non-static method firstValue() cannot be referenced from a static context

为什么它适用于compare()而不适用于compare()。thenComparing()?

Why does it work for comparing() and not for comparing().thenComparing() ?

推荐答案

该错误似乎与 Pair 的通用参数有关。正如您所尝试的那样,使用显式类型的一种解决方法是:

The error seems to be related to Pair's generic parameters. One workaround it to use an explicit type, as you've attempted:

pairList.sort(Comparator.<Pair>comparingInt(Pair::firstValue).thenComparingInt(Pair::secondValue));
//                       ^^^^^^

注意 comparisonInt ()减少了你需要指定的参数数量,并通过避免装箱来提高性能。

Note the comparingInt() which reduces the number of parameters you need to specify, and improves performance by avoiding boxing.

另一种解决方案是参数化类型参考:

Another solution is to parameterize the type reference:

pairList.sort(Comparator.comparingInt(Pair<?,?>::firstValue).thenComparingInt(Pair::secondValue));
//                                        ^^^^^

这篇关于Java 8 Comparator比较不链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 13:59