问题
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