Java 8 Comparator comparing doesn't chain

前端 未结 2 1422
时光说笑
时光说笑 2020-12-11 02:24

Let\'s say I have a Pair class

public class Pair {
    public P p;
    public Q q;


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


        
2条回答
  •  孤街浪徒
    2020-12-11 03:16

    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.comparingInt(Pair::firstValue).thenComparingInt(Pair::secondValue));
    //                       ^^^^^^
    

    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));
    //                                        ^^^^^
    

提交回复
热议问题