I'm not sure if this small example has syntax errors or if there's an issue with NetBeans 8.1 / Java 8 update 66. The goal here is to use a lambda compare (as opposed to using a custom compare) as shown in one of the answers here:
java: Arrays.sort() with lambda expression
The eventual goal is to sort an array of indices (0 to n-1) according to an array of values, using a lambda compare. With the answer provided by irfani arief to use Integer instead of int, the third code example in this question does this.
I'm using similar syntax, but I'm getting an error on the line that uses the lambda expression. I've tried the variations shown on the linked to question and answers, but nothing has worked yet.
package x;
import java.util.Arrays;
public class x {
public static void main(String[] args) {
int[] A = {3, 1, 2, 0};
Arrays.sort(A, (a, b) -> a-b); //error on this line
for(int i = 0; i < 4; i++)
System.out.println(A[i]);
}
}
Changing to Integer as answered by irfani arief solved the issue.
package x;
import java.util.Arrays;
public class x {
public static void main(String[] args) {
Integer[] A = {3, 1, 2, 0};
Arrays.sort(A, (a, b) -> a-b);
for(int i = 0; i < 4; i++)
System.out.println(A[i]);
}
}
This was the real goal, to sort an array of indices according to an array of values using a lambda compare, similar to the way this can be done with C++ std::sort using a lambda compare. Only the array of indices needs to be Integer type, the array of values can be primitive type.
package x;
import java.util.Arrays;
public class x {
public static void main(String[] args) {
int[] A = {3, 1, 2, 0};
Integer[] I = {0, 1, 2, 3};
Arrays.sort(I, (i, j) -> A[i]-A[j]);
for (Integer i : I) {
System.out.println(A[i]);
}
}
}