Search code examples
javalambdacomparator

Why my lambda is not applicable for comparator?


At first, I write the following code, but it can't build. Arrays.sort(n, (o1 ,o2) -> o1 % 2 == 0 ? 1 : -1); enter image description here

And then , I write another code to test it. Arrays.sort(n,(o1, o2) -> o1 - o2); but it has a same error message in vs code. And then , I try those code in IDEA , and it has different error messages in the following pictureenter image description here it says Operator '-' cannot be applied to 'T', 'T. And then , I rewrite the code : Arrays.sort(n,(int o1, int o2) -> o1 - o2); enter image description here I don't know why my code doesn't work. And I found the code I write yesterday: Arrays.sort(envelopes,(int []o1,int []o2) -> o1[0] == o2[0] ? o2[1] - o1[1] :o1[0] - o2[0]); and it works well.


Solution

  • You're experiencing one of the warts of Java's type system that made the otherwise nicely backwards compatible lambdas awkward — int is a primitive type.

    There are no generics over primitive types (yet), so there is no Comparator<int>. The signature of the sort method you're trying to use is

    public static <T> void sort(T[] a, Comparator<? super T> c)

    and T cannot be int (or short, byte, etc.).

    One way around this is to box your ints, e.g. with a stream:

    Arrays.stream(n).boxed().sorted((i1, i2) -> i1 % 2 == 0 ? 1 : -1)