简体   繁体   English

在java中对二维字符串数组进行排序

[英]Sort 2D String array in java

I am trying to sort a 2D array based on the column and values but never got the result back as i want.我正在尝试根据列和值对 2D 数组进行排序,但从未得到我想要的结果。

public class SortColl {
public static void main(String args[]){
 String[][] multi = new String [][]{
                    {"Josef", "cool"},
                    {"Josef", "bat"},
                    {"zeta", "doen"},
                    {"zeta", "up"},
                    {"root", "local"},
                    {"root", "region"}
     };

Arrays.sort(multi, new Comparator<String[]>(){
    @Override
    public int compare(String[] first, String[] second){
         final String time1 = first[0];
         final String time2 = second[0];
        return time1.compareTo(time2);
    }

});

for (int i=0; i< multi.length; i++){
    String[] row = multi[i];
    for(int j=0; j<row.length;j++){
        System.out.println(" , " + row[j] );
    }

}
}

} }

For the above, I want to get the result as对于上述,我想得到的结果为

{"Josef", "bat"},
{"Josef", "cool"},
{"root", "local"},
{"root", "region"}                  
{"zeta", "doen"},                   
{"zeta", "up"}, 

Can any one please guide me?任何人都可以指导我吗?

You can use the Comparator function, but you have to comprehend how a 2D array is represented in the memory.您可以使用 Comparator 函数,但您必须了解二维数组在内存中的表示方式。

String[][] multi = new String [][]{
    {"Josef", "cool"},
    {"Josef", "bat"},
    {"zeta", "doen"}
};

This means that multi is an array of array.这意味着 multi 是一个数组数组。 The first index of multi is an array with contents "Josef" and "cool". multi 的第一个索引是一个包含“Josef”和“cool”内容的数组。 The second "Josef" and "bat".第二个“约瑟夫”和“蝙蝠”。 And so on.等等。

More visually:更直观:

multi ----> [ ][ ][ ]
             |  |  |
             |  |  \->["zeta", "doen"]
             |  |
             |  \-> ["Josef"]["bat"]
             |
             \-> ["Josef"]["cool"]

When using the Array.sort() , the comparator receives a 1D array as arguments.使用Array.sort() ,比较器接收一维数组作为参数。 So when the arguments are String[] first, String[] second then in memory, you have (when the Array.sort() function is doing the first step)因此,当参数首先是String[] first, String[] second然后是String[] first, String[] second然后在内存中时,您有(当Array.sort()函数执行第一步时)

first --> ["Josef"]["cool"]
second--> ["Josef"]["bat"]

So, in order to sort correctly, you have to check the first element.因此,为了正确排序,您必须检查第一个元素。 If it matches, then check the second element.如果匹配,则检查第二个元素。 Hence I've adapted your comparator class;因此,我调整了您的比较器类;

Arrays.sort(multi, new Comparator<String[]>(){
    @Override
    public int compare(String[] first, String[] second){
        // compare the first element
        int comparedTo = first[0].compareTo(second[0]);
        // if the first element is same (result is 0), compare the second element
        if (comparedTo == 0) return first[1].compareTo(second[1]);
        else return comparedTo;
    }
});

This should do the job.这应该可以完成工作。

Modify your sorting mechanism somewhat like修改你的排序机制有点像

   Arrays.sort(multi, new Comparator<String[]>(){
            @Override
            public int compare(String[] first, String[] second){
                final String time1 = first[0];
                final String time2 = second[0];
                int compare = time1.compareTo(time2);
                if(compare != 0){
                    return compare;
                }else{
                    return first[1].compareTo(second[1]);
                }
            }

        });

You can also write it as in java 8您也可以像在 java 8 中一样编写它

Arrays.sort(multi, (first, second) -> {
    final String time1 = first[0];
    final String time2 = second[0];
    int compare = time1.compareTo(time2);
    if(compare != 0){
        return compare;
    }else{
        return first[1].compareTo(second[1]);
    }
})

The only way I can see of doing this is to separate out into left and right columns, sort those and then rejoin.我能看到的唯一方法是将它们分成左右列,对它们进行排序,然后重新加入。

 String[][] multi = new String [][]{
     {"Josef", "cool"},
     {"Josef", "bat"},
     {"zeta", "doen"},
     {"zeta", "up"},
     {"root", "local"},
     {"root", "region"}
 };

 String [] left = new String[multi.length]; 
 for (int i = 0; i < multi.length; i++) {
     left[i] = multi[i][0];
 }
 Arrays.sort(left);

 String [] right = new String[multi.length]; 
 for (int i = 0; i < multi.length; i++) {
     right[i] = multi[i][1];
 }
 Arrays.sort(right);

 for (int i = 0; i < multi.length; i++) {
     multi[i][0] = left[i];
     multi[i][1] = right[i];
 }

If you are using Java 8 then you can create an element comparator and use that in your sort:如果您使用的是 Java 8,那么您可以创建一个元素比较器并在您的排序中使用它:

private Comparator<String[]> byElement(int i) {
    return Comparator.comparing(a -> a[i]);
}

Arrays.sort(multi, byElement(0).thenComparing(byElement(1)));

Personally I find this a more elegant representation than implementing your own compareTo method.我个人认为这比实现自己的compareTo方法更优雅。 It also makes it trivial to add new elements to the comparison, or reverse one field, or handle nulls first or last etc. with standard Comparator methods rather than custom code.使用标准Comparator方法而不是自定义代码将新元素添加到比较中,或反转一个字段,或首先或最后处理空值等也变得微不足道。

感谢这是一个旧帖子,所以如果将来有人遇到这个:

Arrays.sort(multi, (a,b) -> a[0].compareTo(b[0]));

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

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