按日期对 ArrayList 中的对象进行排序? [英] Sort objects in ArrayList by date?

查看:34
本文介绍了按日期对 ArrayList 中的对象进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到的每个示例都是按字母顺序执行此操作,而我需要按日期对元素进行排序.

Every example I find is about doing this alphabetically, while I need my elements sorted by date.

我的 ArrayList 包含其中一个数据成员是 DateTime 对象的对象.在 DateTime 我可以调用函数:

My ArrayList contains objects on which one of the datamembers is a DateTime object. On DateTime I can call the functions:

lt() // less-than
lteq() // less-than-or-equal-to

为了进行比较,我可以这样做:

So to compare I could do something like:

if(myList.get(i).lt(myList.get(j))){
    // ...
}

我应该在 if 块中做什么?

What should I do inside the if block?

推荐答案

您可以使您的对象具有可比性:

You can make your object comparable:

public static class MyObject implements Comparable<MyObject> {

  private Date dateTime;

  public Date getDateTime() {
    return dateTime;
  }

  public void setDateTime(Date datetime) {
    this.dateTime = datetime;
  }

  @Override
  public int compareTo(MyObject o) {
    return getDateTime().compareTo(o.getDateTime());
  }
}

然后你通过调用对它进行排序:

And then you sort it by calling:

Collections.sort(myList);

但是有时您不想更改模型,例如当您想对几个不同的属性进行排序时.在这种情况下,您可以即时创建比较器:

However sometimes you don't want to change your model, like when you want to sort on several different properties. In that case, you can create comparator on the fly:

Collections.sort(myList, new Comparator<MyObject>() {
  public int compare(MyObject o1, MyObject o2) {
      return o1.getDateTime().compareTo(o2.getDateTime());
  }
});

但是,仅当您确定在比较时 dateTime 不为空时,上述内容才有效.明智的做法是处理 null 以避免 NullPointerExceptions:

However, the above works only if you're certain that dateTime is not null at the time of comparison. It's wise to handle null as well to avoid NullPointerExceptions:

public static class MyObject implements Comparable<MyObject> {

  private Date dateTime;

  public Date getDateTime() {
    return dateTime;
  }

  public void setDateTime(Date datetime) {
    this.dateTime = datetime;
  }

  @Override
  public int compareTo(MyObject o) {
    if (getDateTime() == null || o.getDateTime() == null)
      return 0;
    return getDateTime().compareTo(o.getDateTime());
  }
}

或者在第二个例子中:

Collections.sort(myList, new Comparator<MyObject>() {
  public int compare(MyObject o1, MyObject o2) {
      if (o1.getDateTime() == null || o2.getDateTime() == null)
        return 0;
      return o1.getDateTime().compareTo(o2.getDateTime());
  }
});

这篇关于按日期对 ArrayList 中的对象进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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