I'm using Java 8 and I have a List<Integer[]> results = new ArrayList<>();
It has subarrays as shown here result = [[-6, 1, 5],[-8, 2, 6],[-8, 3, 5]]
. And I want to sort the result based on the 0th and 1st indexes of subarray.
Sorted List: result = [[-8, 2, 6], [-8, 3, 5], [-6, 1, 5]]
.
How can I do it in Java Collections?
I implemented Collections.sort(result, (o1,o2)-> {(o1.get(0) > o2.get(0)) ? 1 : (o1.get(0) < o2.get(0) ? -1 : 0)};);
but its not working as expected.
As per your question, if you just need it sorted based on the first value then I think the following code should work for you :
Integer[] results = {-6, 1, 5};
Integer[] results1 = {-8, 2, 6};
Integer[] results2 = {-8, 3, 5};
List<Integer[]> arrays = new ArrayList<>();
arrays.add(results);
arrays.add(results1);
arrays.add(results2);
Collections.sort(arrays, (o1,o2) -> {
return (o1[0] > o2[0]) ? 1 : (o1[0] < o2[0] ? -1 : 0);
});
arrays.stream()
.forEach(x -> {
Arrays.stream(x).forEach(System.out::print);
System.out.println();
});
The output is :
-826
-835
-615