简体   繁体   English

二维数组中的深度排序

[英]Deep sorting in 2d array

I need to achieve a functionality in java similar to sql sort where in i have a function where i pass a 2d array along with 2 column indexes, this function should return a sorted 2d array on the provided column indexes. 我需要在Java中实现类似于sql sort的功能,其中我有一个函数,其中我将2d数组与2个列索引一起传递,此函数应在提供的列索引上返回已排序的2d数组。

In short I need to sort the 2d array on 2 columns. 简而言之,我需要在2列上对2d数组进行排序。

I was able to achieve the sort on 1 column wise , PFB the code for the same. 我能够在1列上实现排序,PFB的代码相同。

Arrays.sort(arr, new Comparator(){
        private int col ;
         public int compare(Object o1, Object o2) {
    String[] s1 = (String[])o1;
    String[] s2 = (String[])o2;
    return s1[col].compareTo(s2[col]);
    }

    private Comparator init(int var){
    col = var;
    return this;
}
}.init(0)
);

But i need to enhance this functionality to sort based on 2 columns in 2d array. 但是我需要增强此功能以基于2d数组中的2列进行排序。 I request experts to help me out in this. 我要求专家对此提供帮助。

Example Input array 输入数组示例

1 2 3 4
1 8 2 8 
8 6 10 11
5 6 7 8
1 6 2 6 

Output : On sorting with Column 2,3 1 2 3 4 1 6 2 6 5 6 7 8 8 6 10 11 1 8 2 8

Thanks in advance, Raju 在此先感谢Raju

Just compare by the second column when the first ones are equals, like that: 当第一列相等时,只需与第二列进行比较,如下所示:

int equal = s1[col].compareTo(s2[col]);
return equal == 0 ? s1[col2].compareTo(s2[col2]) : equal;

Please also note that you are comparing strings (a lexicographical comparison), not numbers, so "10" would be less then "2", resulting in: 另请注意,您正在比较的是字符串(字典比较),而不是数字,因此“ 10”将小于“ 2”,从而导致:

1 2 3 4 
8 6 10 11 
1 6 2 6 
5 6 7 8 
1 8 2 8 

when you sort by columns 2 and 3. 按第2列和第3列排序时。

If that is not what you want, just convert you data to integers and compare then numerically. 如果这不是您想要的,只需将数据转换为整数,然后进行数值比较即可。

You can also use Comparator.thenComparing to do the same thing: 您还可以使用Comparator.thenComparing执行相同的操作:

thenComparing(Comparator other) Returns a lexicographic-order comparator with another comparator. thenComparing(Comparator other)返回带有另一个比较器的字典顺序比较器。

If this Comparator considers two elements equal, ie compare(a, b) == 0, other is used to determine the order. 如果此比较器认为两个元素相等,即compare(a,b)== 0,则使用其他元素确定顺序。

Arrays.sort(array,
    Comparator.<String[],String>
    comparing(row -> row[1])
   .thenComparing(row2 -> row2[2])
);

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

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