我正在尝试对ArrayList w.r.t termDate进行排序。 ArrayList包含firstName,lastName,email,startDate,termDate,Status
日期可以为空或为空。我必须相应地进行比较,并将所有空/空日期值放在最后。
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
}
}
});
部分sysouts:
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
答案 0 :(得分:2)
根据您的代码,我假设您的日期是 String 对象(当您将它们与空字符串进行比较时),当我查看输出时,日期按字母顺序排序,这是这个假设的预期输出。
解决方案:更改模型并使用LocalDate
(在Java 8上)或Date
(在Java 8之前)作为数据类型。
或者(不推荐),您可以在比较时将字符串转换为LocalDate
(这本身就比较慢)。
答案 1 :(得分:0)
TermDate的类型是什么? 如果是String,则将其解析为日期。 (如果你在这个日期有工作要做,你永远不应该有一个日期的字符串表示) 要比较两个日期,请在一个为null时定义您的comportment, 对于一般情况,返回date1.compareTo(date2)