在这种情况下如何处理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;
    }

但是如何使所有空值和空值都显示在顶部

hufengguang 回答:在这种情况下如何处理nullsFirst

您可以使用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;
本文链接:https://www.f2er.com/3169117.html

大家都在问