Sorting a List of Pairs java [duplicate]

◇◆丶佛笑我妖孽 提交于 2020-01-07 03:18:27

问题


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.

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

Error :

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)

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


回答1:


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


来源:https://stackoverflow.com/questions/57624889/sorting-a-list-of-pairs-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!