如何按某些属性对对象列表进行排序 [英] How to sort List of objects by some property

查看:160
本文介绍了如何按某些属性对对象列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的课程

public class ActiveAlarm {
    public long timeStarted;
    public long timeEnded;
    private String name = "";
    private String description = "";
    private String event;
    private boolean live = false;
}

列表< ActiveAlarm> con。如何按 timeStarted 按升序排序,然后按 timeEnded ?有人可以帮忙吗?我知道在C ++中使用泛型算法和重载运算符<,但我是Java新手。

and List<ActiveAlarm> con. How to sort in ascending order by timeStarted, then by timeEnded? Can anybody help? I know in C++ with generic algorithm and overload operator <, but I am new to Java.

推荐答案

要么 ActiveAlarm 实施 Comparable< ActiveAlarm> 或实施 Comparator< ActiveAlarm> 单独的课程。然后致电:

Either make ActiveAlarm implement Comparable<ActiveAlarm> or implement Comparator<ActiveAlarm> in a separate class. Then call:

Collections.sort(list);

Collections.sort(list, comparator);

一般来说,实现 可比较< T> 如果有一个自然排序顺序...否则(如果你发生想要按特定顺序排序,但可能同样容易想要一个不同的顺序),最好实现 比较器< T> 。这个特殊的情况可能是两种方式,说实话......但我可能坚持使用更灵活的 Comparator< T> 选项。

In general, it's a good idea to implement Comparable<T> if there's a single "natural" sort order... otherwise (if you happen to want to sort in a particular order, but might equally easily want a different one) it's better to implement Comparator<T>. This particular situation could go either way, to be honest... but I'd probably stick with the more flexible Comparator<T> option.

编辑:示例实现:

public class AlarmByTimesComparer implements Comparator<ActiveAlarm> {
  @Override
  public int compare(ActiveAlarm x, ActiveAlarm y) {
    // TODO: Handle null x or y values
    int startComparison = compare(x.timeStarted, y.timeStarted);
    return startComparison != 0 ? startComparison
                                : compare(x.timeEnded, y.timeEnded);
  }

  // I don't know why this isn't in Long...
  private static int compare(long a, long b) {
    return a < b ? -1
         : a > b ? 1
         : 0;
  }
}

这篇关于如何按某些属性对对象列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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