按反向顺序(String,Date等)中的对象</object []>对ArrayList <object []>进行排序

时间:2015-01-27 10:57:33

标签: java sorting arraylist

假设有一个ArrayList<Object[]>包含其中的各种对象:

ArrayList<Object[]> list = new ArrayList<>();
list.add(new Object[]{"cat", (long)1422355945});
list.add(new Object[]{"dog", (long)1422355970});
list.add(new Object[]{"rat", (long)1422355900});

我们如何以相反的顺序首先ObjectString)有效地对此列表进行排序?并在第二个Objectlong)之后执行相同的操作?

1 个答案:

答案 0 :(得分:1)

只需创建一个比较器,类似于以下示例:

    List<Object[]> list = new ArrayList<>();
    list.add(new Object[] { "cat", (long) 1422355945 });
    list.add(new Object[] { "dog", (long) 1422355970 });
    list.add(new Object[] { "rat", (long) 1422355900 });

    Collections.sort(list, new Comparator<Object[]>() {
        @Override
        public int compare(Object[] o1, Object[] o2) {
            int cmp1 = ((String) o1[0]).compareTo((String) o2[0]);
            if (cmp1 == 0) {
                return Long.compare((Long) o1[1], (Long) o2[1]);
            }
            return cmp1;
        }
    });