对对列表进行排序 [英] Sorting a List of Pairs java
问题描述
我已经列出了成对的.我想先根据键对它们进行排序,如果键相同,则根据值进行排序.
I've List with Pairs in it. I want to sort them according to the keys first and if keys are same then sort according to the values.
我尝试了以下代码,但引发了不兼容类型的异常:无法推断类型变量T
I tried following code but throws an exception incompatible types: cannot infer type-variable(s) T
List<Pair<Integer,Integer>> list = new ArrayList<>();
list.sort(Comparator.comparingInt(Pair::getKey).thenComparingInt(Pair::getValue);
错误:
不兼容的类型:无法推断类型变量T (参数不匹配;方法参考无效 类Pair中的getKey方法不能应用于给定类型 必需:无参数 找到:对象 原因:实际参数和正式参数列表的长度不同)
incompatible types: cannot infer type-variable(s) T (argument mismatch; invalid method reference method getKey in class Pair cannot be applied to given types required: no arguments found: Object reason: actual and formal argument lists differ in length)
其中T,K,V是类型变量: T扩展了在方法compareInt(ToIntFunction)中声明的对象 K扩展在类Pair中声明的对象 V扩展了在类对中声明的对象
where T,K,V are type-variables: T extends Object declared in method comparingInt(ToIntFunction) K extends Object declared in class Pair V extends Object declared in class Pair
推荐答案
您需要帮助编译器为比较器推断适当的类型:
You need to help the compiler infer the appropriate type for the comparator:
list.sort(Comparator.<Pair<Integer, Integer>>comparingInt(Pair::getKey).thenComparingInt(Pair::getValue));
这篇关于对对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!