gpt4 book ai didi

java - Collections.sort() 对于日期不起作用

转载 作者:行者123 更新时间:2023-11-30 03:17:34 26 4
gpt4 key购买 nike

我正在尝试对 ArrayList 与 termDate 进行排序。ArrayList 包含名字、姓氏、电子邮件、开始日期、学期日期、状态

日期可以为空或为 null。我必须进行相应的比较,并将所有空/空日期值放在最后。

Collections.sort(usersList, new Comparator<User>() {
public int compare(User o1, User o2) {
System.out.println("Term Date: " + o1.getTermDate() +" " +o2.getTermDate());
if((o1.getTermDate() == null || "".equals(o1.getTermDate())) && (o2.getTermDate() == null || "".equals(o2.getTermDate()))) {
System.out.println("Term Date1: 0 " + o1.getTermDate() + " " + o2.getTermDate());
return 0; //They are both null, both equal
}
if((o1.getTermDate() == null || "".equals(o1.getTermDate())) && (o2.getTermDate() != null || "".equals(o2.getTermDate()))) {
System.out.println("Term Date2: -1 " + o1.getTermDate() + " " + o2.getTermDate());
return -1; // The first is null and the second is not, return the first as lower than the second
}
if((o1.getTermDate() != null || "".equals(o1.getTermDate())) && (o2.getTermDate() == null || "".equals(o2.getTermDate()))) {
System.out.println("Term Date3: 1 " + o1.getTermDate() + " " + o2.getTermDate());
return 1; //The first is not null and the second is, return the first as higher than the second
}
else {
System.out.println("Term Date4: " + o1.getTermDate() + " " + o2.getTermDate());
return o1.getTermDate().compareTo(o2.getTermDate()); //Return the actual comparison
}
}
});

部分系统输出:

Term Date: null 2015-08-31 00:00:00.0
Term Date2: -1 null 2015-08-31 00:00:00.0
Term Date: null null
Term Date1: 0 null null
Term Date: 2015-08-31 00:00:00.0 null
Term Date3: 1 2015-08-31 00:00:00.0 null
Term Date: 2015-08-31 00:00:00.0 null
Term Date3: 1 2015-08-31 00:00:00.0 null
Term Date: 2015-08-31 00:00:00.0 null
Term Date3: 1 2015-08-31 00:00:00.0 null
Term Date: 2015-08-31 00:00:00.0 null
Term Date3: 1 2015-08-31 00:00:00.0 null
Term Date: 2015-08-31 00:00:00.0 2015-08-31 00:00:00.0
Term Date4: 2015-08-31 00:00:00.0 2015-08-31 00:00:00.0

部分输出:

user,five,user5@gmail.com,08/07/2015,,Active
usernew2,two,usernew2@gmail.com,08/11/2015,,Active
myname2,hello3,qwerty1@gmail.com,08/11/2015,,Active
user,noUserAuth,user_nouserauth@gmail.com,08/21/2015,,Active

最佳答案

根据您的代码,我假设您的日期是 String 对象(当您将它们与空字符串进行比较时),当我查看输出时,日期是按字母顺序排序,这是此假设下的预期输出。

解决方案:更改模型并使用 LocalDate (在 Java 8 上)或 Date (Java 8 之前的版本)作为数据类型。或者(不推荐),您可以在比较时将字符串转换为 LocalDate(这本质上会比较慢)。

关于java - Collections.sort() 对于日期不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32207661/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com