0

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

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38

1 Answers1

4

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));
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 4
    Slightly simpler syntax: `list.sort(Comparator.comparingInt(Pair::getKey) .thenComparingInt(Pair::getValue));` – Holger Aug 23 '19 at 11:25