2017-02-20 163 views
0

我有二维数组,它有2列,我想排序这一点。基于两列排序二维数组


输入是这样的:

第一列.....第二列

3 ..................... .2

4 ...................... 9

3 ............... ....... 1

5 ...................... 0

1 ...................... 2


输出是这样的:

第一列.....第二栏

5 ...................... 0

4 ............... ....... 9

3 ...................... 2

3 ....................... 1

1 .................. .... 2


我是Java初学者。

请帮我丝毫的功能的代码(mySort(INT [] [] ARR)到数组排序

+0

我的第二个第一,然后才能做才能通过第一 –

+3

如果你还没有这么做过,那么*请*花一些时间来阅读[帮助。页](http://stackoverflow.com/h elp),尤其是名为[“我可以问什么问题?”](http://stackoverflow.com/help/on-topic)和[“我应该避免问什么类型的问题?”](http ://stackoverflow.com/help/dont-ask)。还请[参观](http://stackoverflow.com/tour)和[阅读如何提出好问题](http://stackoverflow.com/help/how-to-ask)。最后,请学习如何创建[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。 –

回答

1

您可以与您的自定义比较排序:

Arrays.sort(datas, new Comparator<Integer[]>() { 
     @Override 
     public int compare(Integer[] entry1, Integer[] entry2) { 
       if(entry1[0] == entry2[0]){ 
         return entry2[1] - entry1[1]; 
       } 
       return entry2[0] - entry1[0]; 
     } 
}); 
0

当使用Java 8 ,你也可以做这样的:

Comparator<Integer[]> comparator = Comparator.comparing(x -> x[0]) 
    .thenComparing(x -> x[1]); 
    // when 
    Arrays.sort(a, comparator.reversed()); 
+1

您需要添加'.thenComparing(x - > x [1])''。 –

+0

谢谢,我忘了第二栏:) – Beri