gpt4 book ai didi

java - 在这种情况下如何处理 nullsFirst

转载 作者:行者123 更新时间:2023-12-02 09:21:11 24 4
gpt4 key购买 nike

如果字段为空,我如何根据日期对列表进行排序?

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;
}

但是如何让所有null和empty都出现在顶部

最佳答案

您可以使用try-catch来捕获异常并返回一些值-101 发生异常时根据排序顺序

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;

关于java - 在这种情况下如何处理 nullsFirst,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58687171/

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