java - 在这种情况下如何处理 nullsFirst
问题描述
如果字段为空,我如何根据日期对列表进行排序?
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
class Person implements Comparable < Person > {
private String name;
private String birthdate;
public Person(String name, String birthdate) {
this.name = name;
this.birthdate = birthdate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
@Override
public int compareTo(Person otherPerson) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
LocalDate currentPersonDate = LocalDate.parse(birthdate, formatter);
LocalDate otherPersonDate = LocalDate.parse(otherPerson.getBirthdate(), formatter);
int retVal = otherPersonDate.compareTo(currentPersonDate); // 1 Comparing With Dates DESC
return retVal;
}
}
// 2009-06-23 00:00:00.0
public class TestClient {
public static void main(String args[]) {
ArrayList < Person > personList = new ArrayList < Person > ();
Person p1 = new Person("Shiva ", "2020-09-30 00:00:00.0");
Person p2 = new Person("pole", "2020-09-30 00:00:00.0");
Person p3 = new Person("Balal ", "");
personList.add(p1);
personList.add(p2);
personList.add(p3);
Collections.sort(personList);
System.out.println("After Descending sort");
for(Person person: personList){
System.out.println(person.getName() + " " + person.getBirthdate());
}
}
}
我使用 Java 8 处理了如下所示的代码
@Override
public int compareTo(Person other) {
try
{
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
return Comparator.comparing((Person student) -> LocalDate.parse(student.getBirthdate(), formatter)).reversed()
.compare(this, other);
}
catch(Exception e)
{
}
return -1;
}
但是如何让所有空值和空值出现在顶部
解决方案
您可以try-catch
用于捕获异常并返回一些值-1
,0
或者1
在出现异常时根据排序顺序
try {
LocalDate currentPersonDate = LocalDate.parse(birthdate, formatter);
LocalDate otherPersonDate = LocalDate.parse(otherPerson.getBirthdate(), formatter);
return otherPersonDate.compareTo(currentPersonDate);
}catch(Exception ex) {
//log error
}
return -1;
推荐阅读
- django - Django REST Framework 按外键过滤
- python - Tensorflow/Keras GPU 使用率低:Jupyter Notebook 似乎是在 CPU 而不是 GPU 上进行训练
- python - 计算连续行之间的秒数差异为第一行返回 NaN
- excel - 根据 Excel 中的另一个单元格值验证单元格
- javascript - 如何调用主应用程序文件的函数?反应原生
- java - 如何使用视频视图和意图播放视频
- node.js - Docker 在 docker-compose up 上同时运行 Yarn update 和 npm update
- firebase - 客户的 GCP 结算帐号
- go - 测试用例中的 Golang 数据竞争条件
- android - 从 Android Sudio 3.2.1 切换到 4.1.2 后的 java.lang.UnsatisfiedLinkError