How to sort List<Integer[]> in java?

969 Views Asked by At

I declared List<Integer[]> results = new ArrayList<>(); in java 8.

And result = [[-6, 1, 5],[-8, 2, 6],[-8, 3, 5]]. I want to sort the result to this result = [[-8, 2, 6], [-8, 3, 5], [-6, 1, 5]]. How can i do it in java?

I implemented Collections.sort(result, (o1,o2)-> {(o1.get(0) > o2.get(0)) ? 1 : (o1.get(0) < o2.get(0) ? -1 : 0)};);

but this code snippet is causing an error.

1

There are 1 best solutions below

0
Ananthapadmanabhan On BEST ANSWER

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