Java 8 Comparator comparing doesn't chain

前端 未结 2 1413
时光说笑
时光说笑 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:07

    It should be:

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

    First type parameter refers to the type being passed to Comparator. Second type parameter refers to the type that comparator should effectively compare with.

    0 讨论(0)
  • 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.<Pair>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));
    //                                        ^^^^^
    
    0 讨论(0)
提交回复
热议问题