我在 ArrayList
中有 10 个对象,其中患者 ID 和预约日期作为实例变量。如何按预约日期对患者进行排序?
出于某种原因,我无法使用Comparator
对ArrayList
进行排序;编译器报错:
java.util.Comparator is abstract; cannot be instantiated
Collections.sort()
在不使用 Comparator
时对 Object
不起作用。
ArrayList<Appointment> testApp = new ArrayList<>();
while (!App.isEmpty()) {
tempA = (Appointment) App.dequeue();
if (tempA.getPatID().equals(search)) {
testApp.add(tempA);
}
tempApp.enqueue(tempA);
}
while (!tempApp.isEmpty()) {
tempA = (Appointment) tempApp.dequeue();
App.enqueue(tempA);
}
Collections.sort(testApp, new Comparator<Appointment>());
最佳答案
我假设您的 Appointment
类看起来像这样:
class Appointment {
private int patientId;
private LocalDateTime appointmentDate;
// Getters & setters
}
如果是这样,您将创建一个 Comparator
以使用 Comparator.comparing
进行排序方法:
ArrayList<Appointment> appointments = new ArrayList<>();
Collections.sort(appointments, Comparator.comparing(appointment -> {
return appointment.getAppointmentDate();
}));
该 lambda 函数告诉比较器如何获取您的对象(Appointment
)并提取用于排序的元素(键;appointmentDate
)。如果您愿意,可以将其压缩为方法引用:
Collections.sort(appointments, Comparator.comparing(Appointment::getAppointmentDate));
您也可以调用Collection#sort()
直接在 ArrayList
上:
appointments.sort(Comparator.comparing(Appointment::getAppointmentDate));
如果您总是(或通常)按日期对Appointment
对象进行排序,您可以考虑让Appointment
实现Comparable
这样您就可以在不传递 Comparator
的情况下调用 .sort()
:
class Appointment implements Comparable<Appointment> {
private int patientId;
private LocalDateTime appointmentDate;
// Getters & setters
@Override
public int compareTo(final Appointment other) {
return appointmentDate.compareTo(other.appointmentDate);
}
}
关于java - 按日期和时间对 ArrayList 的对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56621200/