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

时间:2020-06-26 01:24:03

标签: java

我想对二维数组列表进行排序。 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)));
         }

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

1 个答案:

答案 0 :(得分:2)

有几种方法可以做到这一点。我选择演示使用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 = o2.get(i).compareTo(o1.get(i));
            if (result != 0) {
                return result;
            }
        }

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