按第一列然后第二列对arraylist排序

Rui :

我想对一个二维数组列表进行排序。a定义为:ArrayList<ArrayList<String>> a = new ArrayList<ArrayList<String>>()目前,我将能够按数组的第一列对其进行排序。但是现在,在按第一列排序之后,如果有平局,我想通过比较第二列进一步对其进行排序。第一列是字符串号(例如"1"),第二列是名称。这是我当前用于比较第一列的代码

Collections.sort(a, new Comparator<ArrayList<String>>() {    
      public int compare(ArrayList<String> o1, ArrayList<String> o2) {
              return -(o1.get(0).compareTo(o2.get(0)));
         }

我应该如何修改它以便可以比较第一列和第二列?

mlaota:

我有几种方法可以做到这一点。我选择演示使用for循环和内联比较器来保持与您的实现尽可能一致:

Collections.sort(a, new Comparator<ArrayList<String>>() {    
    /** 
    * The idea is that we want to keep comparing the two lists if
    * there is a tie. We do this by leveraging an early return. There
    * are a couple edge cases dealing with the cases of the first N 
    * elements of o1 matching the first N elements of o2 where N is
    * the length of the smaller list. I will leave it to you to think 
    * about what you want to happen in these cases.
    */
    public int compare(ArrayList<String> o1, ArrayList<String> o2) {

        // This ensures that we don't exceed the bounds of either list.
        int sizeOfSmallerList = Math.min(o1.size(), o2.size());

        // Compare the elements at each position of the lists until 
        // a non-matching position is found.
        for (int i = 0; i < sizeOfSmallerList; i++) {
            int result = -(o1.get(i).compareTo(o2.get(i)));
            if (result != 0) {
                return result;
            }
        }

        return ...result when first sizeOfSmallerList elements are the same in o1 and o2...;
    }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

按第一列然后第二列对文件进行排序

按第一列对2d数组进行排序,然后对第二列进行排序

首先按第一列然后按第二列对2D列表进行排序

按第二列和第一列对二维数组进行排序

如何在文本上按第一列进行排序,然后用'sort'按数字进行第二排序?

按第三列排序,在Linux中完整保留第一列和第二列?

Postgresql 按第一列排序,但在第二列最后有空值或零

MySQL:按第二列排序——如果不為空——同時保持第一列順序

JavaScript排序功能。按第一,然后第二

MySQL根据第一列对第二列和第三列进行排序

我如何从(第一)列开始,然后(第二)另一列是特定的开始时间来排序我的行?

SQL-根据第一列排序第二列

相对于第一列对第二列进行排序

如果第一列显示相等的值,如何使用第二列进行排序

熊猫按第一列分组,并从第二列添加逗号分隔的条目

按第一列分组,第二列的结果作为xml

将一列相加,然后减去第二列

如何按Excel或GSheet中第二列的值对第一列中具有相等值的列表进行排序?

按第一列删除重复项,但保留第二个

通过第一列 id 检查第二列

如果第一列匹配,则处理第二列

如何比较第一列和第二列

CSS - 第二列内容进入第一列

从第一列的两列查找到第二列的第二列查找

比较 2 列;当第一列>第二列时,删除第二列

按一列排序,然后按另一列排序

根据第二个字段排序,然后重新排序具有相同第一列的行,但仍保持每个组的第二个字段的顺序

如何按升序对第一行然后在第二行和最后在第三行中的数字进行排序但保存列顺序?

按python中的第一(或第二,否则)列对文件排序