需要帮助的排序由第二个元素的二维数组,然后通过一个元素(JAVA) [英] Need help sorting two dimensional arrays by second element and then by first element (Java)

查看:83
本文介绍了需要帮助的排序由第二个元素的二维数组,然后通过一个元素(JAVA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个保持的5张牌的值的二维阵列。每个5阵列中的第一个元素重新presents卡的套装,并重新$ P $的第二个元素psents卡值。

I have a two dimensional array that is holding the value of 5 cards. The first element of each of the 5 arrays represents the suit of the card, and the second element represents the card value.

我想,同时保持第二元件的排序,以便通过所述第二元件的二维阵列由第一元件排序,然后(如果这是很有意义的)。例如那些的所有诉讼将在排序列表超过两所有诉讼较低。因此,例如,{{0,1},{2,1},{0,2}}应该成为{{0,1},{2,1},{0,2}}

I want to sort the 2d array by the second element, and then by the first element while maintaining the sorted order of the second element (if that makes sense). For example all suits of ones will be lower on the sorted list than all suits of two. So for example, {{0,1},{2,1},{0,2}} should become {{0,1},{2,1},{0,2}}.

下面是我:

 // {{3,2}, {2,2}, {0,1}, {1,0}, {2,3}} should become 
 // {{1,0}, {0,1}, {2,2}, {3,2}, {2,3}}

 int[][] hand = {{3,2},{2,2},{0,1},{1,0},{2,3}};
 sort(hand);

 public static void sort(int[][] hand){
    Arrays.sort(hand, new Comparator<int[]>(){
        public int compare(int[] o1, int[] o2){
            return Integer.valueOf(o1[1]).compareTo(Integer.valueOf(o2[1]));
        }
    });
 }

这是输出{{1,0},{0,1},{3,2},{2,2},{2,3}}。有没有人有什么建议?

This is outputting {{1,0},{0,1},{3,2},{2,2},{2,3}}. Does anyone have any suggestions?

推荐答案

解决方案1:通过所述第二元件的阵列排序,然后被第一元件阵列排序。由于 Arrays.sort 是稳定的,这相当于先通过第一个元素,那么第二。

Solution 1: sort the arrays by the second element, and then sort the arrays by the first element. Since Arrays.sort is stable, that's equivalent to first comparing by the first element, then the second.

解决方案2:修改你的比较如下:

Solution 2: modify your comparator as follows:

Arrays.sort(hand, new Comparator<int[]>() {
  public int compare(int[] o1, int[] o2) {
    if (o1[0] == o2[0]) {
      return Integer.compare(o1[1], o2[1]);
    } else {
      return Integer.compare(o1[0], o2[0]);
    }
  }
});

或与番石榴(披露:我贡献番石榴),你可以只写比较为

or, with Guava (disclosure: I contribute to Guava), you can just write the comparator as

  public int compare(int[] o1, int[] o2) {
    return ComparisonChain.start()
      .compare(o1[0], o2[0])
      .compare(o1[1], o2[1])
      .result();
  }

这篇关于需要帮助的排序由第二个元素的二维数组,然后通过一个元素(JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆