【问题标题】:Sort ArrayList by Objects containing three values [duplicate]按包含三个值的对象对ArrayList进行排序[重复]
【发布时间】:2013-03-11 11:21:07
【问题描述】:

我有一个包含三个值的 ArrayList,现在我想按这些值对它们进行排序:

List<AvailablePeriod> periodList = new ArrayList<AvailablePeriod>

AvailablePeriod 对象包含:

DateTime start
DateTime end
int id

我希望列表中的对象首先按开始排序,而不是结束和最后按 id 排序。

无法弄清楚排序..

【问题讨论】:

标签: java list sorting arraylist


【解决方案1】:

xyz 类实现 Comparable { 日期时间开始; 日期时间结束; 内部标识; @Override public int compareTo(xyz o) { if (this.start.isBefore(o.start)) { return -1; } else if (o.start.isBefore(o.start)) { return -1; } else { if (this.end.isBefore(o.end)) { return -1; } else if (o.end.isBefore(this.end)) { return 1; } else { if (this.id > o.id) { return 1; } else if (this.id < o.id) { return -1; } else { return 0; } } } } }

你可以这样写。然后使用collections.sort(list)

【讨论】:

    【解决方案2】:

    如下写一个比较器

       public class MyComparator implements Comparator<AvailablePeriod> {
        @Override
        public int compare(AvailablePeriod o1, AvailablePeriod o2) {
            int result = o1.getStart().compareTo(o2.getStart());
            if (result == 0) {
                result = o1.getEnd().compareTo(o2.getEnd());
            }
            if (result == 0) {
                result = Integer.valueOf(o1.getId()).compareTo(o2.getId());
            }
            return result;
        }
       }
    

    然后使用 Collection.sort 方法

    List<AvailablePeriod> periodList = new ArrayList<AvailablePeriod>
    Collections.sort(periodList , new MyComparator());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 2012-01-17
      • 1970-01-01
      • 2013-05-21
      • 1970-01-01
      相关资源
      最近更新 更多