Java 是否按日期对ArrayList中的对象排序?

Java 是否按日期对ArrayList中的对象排序?,java,sorting,datetime,Java,Sorting,Datetime,我找到的每个示例都是关于按字母顺序执行此操作的,而我需要按日期对元素进行排序 My ArrayList包含其中一个DataMember是DateTime对象的对象。在DateTime,我可以调用以下函数: lt() // less-than lteq() // less-than-or-equal-to 因此,为了进行比较,我可以这样做: if(myList.get(i).lt(myList.get(j))){ // ... } 在if块内应该做什么?您可以使用Collections

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

My ArrayList包含其中一个DataMember是DateTime对象的对象。在DateTime,我可以调用以下函数:

lt() // less-than
lteq() // less-than-or-equal-to
因此,为了进行比较,我可以这样做:

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

在if块内应该做什么?

您可以使用Collections.sort方法。这是一种静态方法。您将列表和比较器传递给它。它在列表上使用修改的mergesort算法。这就是为什么必须传递一个比较器来进行配对比较

Collections.sort(myList, new Comparator<MyObject> {
   public int compare(MyObject o1, MyObject o2) {
      DateTime a = o1.getDateTime();
      DateTime b = o2.getDateTime();
      if (a.lt(b)) 
        return -1;
      else if (a.lteq(b)) // it's equals
         return 0;
      else
         return 1;
   }
});
Collections.sort(myList,新的比较器{
公共整数比较(MyObject o1,MyObject o2){
DateTime a=o1.getDateTime();
DateTime b=o2.getDateTime();
如果(a.lt(b))
返回-1;
如果(a.lteq(b))//它等于
返回0;
其他的
返回1;
}
});

请注意,如果myList属于可比较类型(实现可比较接口的类型)(如日期、整数或字符串),则可以省略比较器,并使用自然排序。

给定的
MyObject
具有
DateTime
成员和
getDateTime()
方法,您可以按
DateTime
对象对包含
MyObject
元素的
ArrayList
进行排序,如下所示:

Collections.sort(myList, new Comparator<MyObject>() {
    public int compare(MyObject o1, MyObject o2) {
        return o1.getDateTime().lt(o2.getDateTime()) ? -1 : 1;
    }
});
Collections.sort(myList,newcomparator(){
公共整数比较(MyObject o1,MyObject o2){
返回o1.getDateTime().lt(o2.getDateTime())?-1:1;
}
});

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

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());
  }
}
但是,有时您不想更改模型,例如当您想对几个不同的属性进行排序时。在这种情况下,您可以动态创建比较器:

Collections.sort(myList, new Comparator<MyObject>() {
  public int compare(MyObject o1, MyObject o2) {
      return o1.getDateTime().compareTo(o2.getDateTime());
  }
});
Collections.sort(myList,newcomparator(){
公共整数比较(MyObject o1,MyObject o2){
返回o1.getDateTime().compareTo(o2.getDateTime());
}
});
但是,只有在比较时确定dateTime不为null时,上述方法才有效。明智的做法是同时处理null以避免NullPointerException:

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());
  }
}
公共静态类MyObject实现可比较{
私人日期时间;
公共日期getDateTime(){
返回日期时间;
}
公共无效setDateTime(日期日期时间){
this.dateTime=dateTime;
}
@凌驾
公共内部比较(MyObject o){
if(getDateTime()==null | | o.getDateTime()==null)
返回0;
返回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());
  }
});
Collections.sort(myList,newcomparator(){
公共整数比较(MyObject o1,MyObject o2){
如果(o1.getDateTime()==null | | o2.getDateTime()==null)
返回0;
返回o1.getDateTime().compareTo(o2.getDateTime());
}
});

对于一个简单的问题,我发现这里的所有答案都不一定复杂(至少对于一个有经验的java开发人员来说,我不是)。我有一个类似的问题,并偶然发现了这个(和其他)解决方案,虽然它们提供了一个指针,但对于一个初学者,我发现如上所述。我的解决方案取决于日期在对象中的位置,在本例中,日期是对象[]的第一个元素,其中dataVector是包含对象的ArrayList

Collections.sort(dataVector, new Comparator<Object[]>() {
    public int compare(Object[] o1, Object[] o2) {
        return ((Date)o1[0]).compareTo(((Date)o2[0]));
    }
});
Collections.sort(dataVector,newcomparator(){
公共整数比较(对象[]o1,对象[]o2){
返回((日期)o1[0])。比较((日期)o2[0]);
}
});

随着Java 1.8的推出,streams在解决此类问题时非常有用:

Comparator <DateTime> myComparator = (arg1, arg2) 
                -> {
                    if(arg1.lt(arg2)) 
                       return -1;
                    else if (arg1.lteq(arg2))
                       return 0;
                    else
                       return 1;
                   };

ArrayList<DateTime> sortedList = myList
                   .stream()
                   .sorted(myComparator)
                   .collect(Collectors.toCollection(ArrayList::new));
Comparator myComparator=(arg1、arg2)
-> {
如果(arg1.lt(arg2))
返回-1;
else if(arg1.lteq(arg2))
返回0;
其他的
返回1;
};
ArrayList sortedList=myList
.stream()
.已排序(myComparator)
.collect(收集器.toCollection(ArrayList::new));

这可能是一个旧的响应,但我使用了本文中的一些示例创建了一个比较器,该比较器将根据列表中的一个对象(即时间戳)对
哈希映射的
数组列表进行排序

我有这些物品:

ArrayList<Map<String, String>> alList = new ArrayList<Map<String, String>>();
现在,我可以随时在数组上调用比较器,它将对数组进行排序,给我位置0(列表顶部)的最新时间戳和列表末尾的最早时间戳。新的职位基本上都被放在了最高层

Collections.sort(alList, new DateSorter());
这可能会帮助某人,这就是我发布它的原因。考虑compare()函数中的返回语句。有三种类型的结果。如果它们相等,则返回0;如果第一个日期在第二个日期之前,则返回>0,并返回这就是我解决问题的方法:

Collections.sort(MyList, (o1, o2) -> o1.getLastModified().compareTo(o2.getLastModified()));

希望对您有所帮助。

在参数中传递ArrayList

    private static void order(ArrayList<Object> list) {

    Collections.sort(list, new Comparator() {

        public int compare(Object o2, Object o1) {

            String x1 =  o1.Date;
            String x2 =  o2.Date;

                return  x1.compareTo(x2);

        }
    });
}
私有静态无效订单(ArrayList列表){
Collections.sort(list,newcomparator(){
公共整数比较(对象o2、对象o1){
字符串x1=o1.日期;
字符串x2=o2.日期;
返回x1.compareTo(x2);
}
});
}
由于Java 8,接口提供了方法。结合表达式,最简单的解决方案是

// sort DateTime typed list
list.sort((d1,d2) -> d1.compareTo(d2));
// or an object which has an DateTime attribute
list.sort((o1,o2) -> o1.getDateTime().compareTo(o2.getDateTime()));
// or like mentioned by Tunaki
list.sort(Comparator.comparing(o -> o.getDateTime()));
反向排序

Java8还提供了一些方便的反向排序方法

//requested by lily
list.sort(Comparator.comparing(o -> o.getDateTime()).reversed());

Tunaki使用Java 8 lambda的最佳答案是使用以下方法确定日期是否排序

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");

boolean  decendingOrder = true;
    for(int index=0;index<date.size() - 1; index++) {
        if(simpleDateFormat.parse(date.get(index)).getTime() < simpleDateFormat.parse(date.get(index+1)).getTime()) {
            decendingOrder = false;
            break;
        }
    }
    if(decendingOrder) {
        System.out.println("Date are in Decending Order");
    }else {
        System.out.println("Date not in Decending Order");
    }       
}   
SimpleDataFormat SimpleDataFormat=新的SimpleDataFormat(“dd-MM-yyyy”);
布尔DecentingOrder=true;

对于(int index=0;indexDate类已经实现了Comparator接口。假设您有以下类:

public class A {

    private Date dateTime;

    public Date getDateTime() {
        return dateTime;
    }

    .... other variables

}
假设您有一个对象列表,如
列表列表列表
,您可以使用Java 8的流API(下面的代码片段)轻松地对其进行排序:


未来的观众,我认为这是最简单的解决方案,如果您的模型包含字符串类型的日期(“20”)
//requested by lily
list.sort(Comparator.comparing(o -> o.getDateTime()).reversed());
list.sort(Comparator.comparing(o -> o.getDateTime()));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");

boolean  decendingOrder = true;
    for(int index=0;index<date.size() - 1; index++) {
        if(simpleDateFormat.parse(date.get(index)).getTime() < simpleDateFormat.parse(date.get(index+1)).getTime()) {
            decendingOrder = false;
            break;
        }
    }
    if(decendingOrder) {
        System.out.println("Date are in Decending Order");
    }else {
        System.out.println("Date not in Decending Order");
    }       
}   
public class A {

    private Date dateTime;

    public Date getDateTime() {
        return dateTime;
    }

    .... other variables

}
import java.util.Comparator;
import java.util.stream.Collectors;

...

aList = aList.stream()
        .sorted(Comparator.comparing(A::getDateTime))
        .collect(Collectors.toList())
Collections.sort(messages, (o1, o2) -> o2.getMessageDate().compareTo(o1.getMessageDate()));
Mylist.sort(Comparator.comparing(myClass::getStarttime));