简体   繁体   English

使用Java比较器对2d数组排序

[英]Sorting 2d arrays using Java Comparator

I have a 2d array called interval[g][2] where g is some number. 我有一个称为interval [g] [2]的二维数组,其中g是一些数字。 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 : 1)使用Java 8的Comparator.comparing方法

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

2) Using Arrays.sort : 2)使用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? 有人可以建议吗?

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 : 或者,如果您想使用自定义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;
     }
 });
int[][] interval = new int[][] { {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} };

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

Stream.of(interval).forEachOrdered(ints -> System.out.println(Arrays.toString(ints)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM