首页 > 解决方案 > 排序对列表java

问题描述

我已经列出了其中的对。我想先根据键对它们进行排序,如果键相同,则根据值进行排序。

我尝试了以下代码,但抛出异常不兼容类型:无法推断类型变量 T

 List<Pair<Integer,Integer>> list = new ArrayList<>();
 list.sort(Comparator.comparingInt(Pair::getKey).thenComparingInt(Pair::getValue);

错误 :

不兼容的类型:无法推断类型变量 T (参数不匹配;类 Pair 中的无效方法引用方法 getKey 不能应用于所需的给定类型:未找到参数:对象原因:实际参数列表和形式参数列表的长度不同)

其中 T,K,V 是类型变量: T 扩展在方法 comparisonInt(ToIntFunction) 中声明的对象 K 扩展在类 Pair 中声明的对象 V 扩展在类 Pair 中声明的对象

标签: javajava-8

解决方案


您需要帮助编译器推断比较器的适当类型:

list.sort(Comparator.<Pair<Integer, Integer>>comparingInt(Pair::getKey).thenComparingInt(Pair::getValue));

推荐阅读