首页 > 解决方案 > Java集合排序通过比较器给出错误

问题描述

我尝试使用 Collections 对 Java ArrayList 进行排序,但它不起作用,即使我尝试遵循其他问题的代码。

我有一个名为 PcdPoint 的类,它具有 getScore() 和 getType() 方法,其中 getScore() 返回一个双精度数,而 getType() 返回一个整数。(不是原子的)

以下代码应该可以工作,但它给了我一个错误:“无法推断类型 <any>”

Collections.sort(pointList,
            Comparator.comparing((PcdPoint a, PcdPoint b) -> a.getScore() - b.getScore())
            .thenComparing((PcdPoint a, PcdPoint b) -> a.getType() - b.getType()));

所以我尝试查找文档并尝试这样做

Collections.sort(pointList,
            Comparator<PcdPoint>.comparing((a, b) -> a.getScore() - b.getScore())
            .thenComparing((a, b) -> a.getType() - b.getType()));

Collections.sort(pointList,
            Comparator.comparing((a, b) -> a.getScore() - b.getScore())
            .thenComparing((a, b) -> a.getType() - b.getType()));

但这些似乎都不起作用。

标签: sortingcollectionsjava-8

解决方案


如果您想先按分数排序,然后按类型排序,您的比较器应该如下所示。

Collections.sort(pointList, 
    Comparator.comparingDouble(PcdPoint::getScore)
        .thenComparingInt(PcdPoint::getType));

推荐阅读