如何比较学生对象

时间:2019-08-29 10:43:41

标签: java

如何比较学生对象

我的代码

如何比较学生对象 如何比较学生对象
如何比较学生对象 如何比较学生对象

import java.time.format.DateTimeFormatter;
import java.util.Comparator;

public class Student implements Comparable < Student >{

    private String studentName;
    private String studentDOJ;

    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public String getStudentDOJ() {
        return studentDOJ;
    }
    public void setStudentDOJ(String studentDOJ) {
        this.studentDOJ = studentDOJ;
    }


  @Override
        public int compareTo(Student other) {
             DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
             return Comparator.comparing(LocalDate.parse(Student::getStudentDOJ,formatter)).reversed()
                     .compare(this, other);
        }

}

2 个答案:

答案 0 :(得分:0)

您不能在此处使用方法引用。

LocalDate.parse(CharSequence, DateTimeFormatter)不需要Function<Student, String>,因此您不能通过Student::getStudentDOJ

@Override
public int compareTo(Student other) {
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
  return Comparator.comparing((Student student) -> LocalDate.parse(student.getStudentDOJ(), formatter)).reversed()
      .compare(this, other);
}

答案 1 :(得分:0)

您可以这样重写方法:

@Override
public int compareTo(Student other) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    return LocalDate.parse(getStudentDOJ(),formatter)
            .compareTo(LocalDate.parse(other.getStudentDOJ(),formatter));
}

并且可以将List<Student>类型的学生列表排序为:

lists.sort(Comparator.reverseOrder()); // dsc
lists.sort(Comparator.naturalOrder()); // asc