While initializing collections like TreeMap
, TreeSet
, etc. We can add our custom comparator.
The code looks something like:
Map<Integer, String> map1 = new TreeMap<>(new Comparator<Integer>() {
public int compare(Integer x, Integer y) {
return x-y;
}
});
Now, we can make replace this anonymous implementation with a lambda expression. The code would look like:
Map<Integer, String> map2 = new TreeMap<>((x,y) -> x-y);
Java-8 allows you to store lambda expressions in a variable through functional interfaces. So, I modified the above code to the following:
BiFunction<Integer, Integer, Integer> myComparator = (x,y) -> x-y;
Map<Integer, String> map3 = new TreeMap<>(myComparator);
But this last attempt did not work! It gave the following error:
Cannot infer type arguments for TreeMap<>
Why did it fail to resolve types in the last example?
Note: To confirm that this is not an IDE bug, I performed a raw compile using javac
and it still gave the same error.
Comparator<Integer> myComparator = (x,y) -> x-y;
instead ofBiFunction
? SinceComparator
is explicitly the type theTreeMap
constructor requires. – khelwood Apr 12 '19 at 14:25Integer.compare(int,int)
doing the right thing, but usually, when you end up comparing twoint
values, you can use eitherComparator.naturalOrder()
,Comparator.reverseOrder()
,Comparator.comparingInt(…)
, or a combination of them. – Holger Apr 12 '19 at 14:55