Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting 2d arrays using Java Comparator

I have a 2d array called interval[g][2] where g is some number. Currently, I'm trying to sort the array first by increasing order in the first element, and if they are equal, sort by decreasing order in the second element.

I've attempted this in two ways:

1) Using Java 8's Comparator.comparing method:

Arrays.sort(interval, Comparator.comparing((int[] arr) -> arr[0]));

2) Using Arrays.sort:

Arrays.sort(interval, new Comparator<int[]>() {
    @Override
    public int compare(int[] s1, int[] s2) {
        if (s1[0] > s2[0])
            return 1;
        else if (s1[0] < s2[0])
            return -1;
        else {
            if(s1[1] < s2[1])
                return 1;
            else if (s1[1] > s2[1])
                return -1;
            else
                return 0;
        }
    }
});

The first method returns a partially sorted list.

[[0, 10], [10, 30], [30, 50]]
[[0, 10], [3, 19], [35, 45]]
[[10, 30], [27, 33], [30, 50]]
[[-10, 10], [0, 20], [35, 45]]
[[10, 30], [20, 40], [30, 50]]
[[0, 20], [8, 28], [37, 43]]
[[0, 20], [15, 35], [37, 43]]
[[0, 0], [8, 28], [10, 40]]

As you can see, it's sorting things in a set of three tuples.

The second method doesn't sort the array at all. Can I not sort using primitive data types? Can anyone advise?

like image 249
viviboox3 Avatar asked Jul 22 '26 00:07

viviboox3


1 Answers

I think you're looking for this:

Arrays.sort(interval, Comparator.comparingInt((int[] arr) -> arr[0]).thenComparing(Comparator.comparingInt((int[] arr) -> arr[1]).reversed()));

Or if you want to go with the custom Comparator:

 Arrays.sort(interval, new Comparator<int[]>() {
     @Override
     public int compare(int[] o1, int[] o2) {
         int result = Integer.compare(o1[0], o2[0]);
         if (result == 0) {
             result = Integer.compare(o2[1], o1[1]);
         }
         return result;
     }
 });
like image 155
shmosel Avatar answered Jul 23 '26 15:07

shmosel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!