gpt4 book ai didi

java - 比较具有涉及 boolean 值的多个属性的列表

转载 作者:搜寻专家 更新时间:2023-11-01 02:07:07 25 4
gpt4 key购买 nike

我有一些实现比较器接口(interface)的类通过添加患者对象对 ArrayList 进行排序,我想按多个属性对列表进行排序并且仅使用枚举进行排序没有问题,但是我想通过使用排序来覆盖这种排序 boolean 值。我知道我不能使用 compareTo 方法,因为它不是 Wrapper 类,但我无法找到合适的方法通过 boolean 对列表进行排序。

如有任何帮助,我们将不胜感激。

    public Patient(int nhsNumber, String name, Status triage, boolean previouslyInQueue, boolean waitingTime){
this.nhsNumber = nhsNumber;
this.name = name;
this.triage = triage;
this.previouslyInQueue = previouslyInQueue;
this.waitingTime = waitingTime;

}

这是我的比较类

public class PatientInQueueComparator implements Comparator<Patient> {

@Override
public int compare(Patient p1, Patient p2) {

if(p1.isPreviouslyInQueue() && !p2.isPreviouslyInQueue()){
return 1;
}else if(p1.isPreviouslyInQueue() && p2.isPreviouslyInQueue()){
return -1;
}
return 0;
}

我的主要方法

List<Patient> queue = new ArrayList<Patient>();

queue.add(new Patient(1, "Bob", Status.URGENT, true, false)); //1st
queue.add(new Patient(2, "John", Status.EMERGENCY, false, false)); //5th
queue.add(new Patient(3, "Mary", Status.NON_URGENT, false, false)); //6th
queue.add(new Patient(4, "Luke", Status.SEMI_URGENT, false, true)); //4th
queue.add(new Patient(5, "Harry", Status.NON_URGENT, true, false)); //2nd
queue.add(new Patient(6, "Mark", Status.URGENT, false, true)); //3rd


System.out.println("*** Before sorting:");

for (Patient p1 : queue) {
System.out.println(p1);
}

Collections.sort(queue, new PatientComparator(
new PatientInQueueComparator(),
new PatientTriageComparator())
);

System.out.println("\n\n*** After sorting:");

for (Patient p1 : queue) {
System.out.println(p1);
}

患者比较器

    private List<Comparator<Patient>> listComparators;

@SafeVarargs
public PatientComparator(Comparator<Patient>... comparators) {
this.listComparators = Arrays.asList(comparators);
}

@Override
public int compare(Patient p1, Patient p2) {
for (Comparator<Patient> comparator : listComparators) {
int result = comparator.compare(p1, p2);
if (result != 0) {
return result;
}
}
return 0;
}

最佳答案

如果您希望 true 值大于 false,您必须更正你的 compare() 方法:

@Override
public int compare(Patient p1, Patient p2) {

if (p1.isPreviouslyInQueue() && !p2.isPreviouslyInQueue())
return -1;
if (!p1.isPreviouslyInQueue() && p2.isPreviouslyInQueue())
return 1;
return 0;
}

通知第二个if。另一个实现可能是:

@Override
public int compare(Patient p1, Patient p2) {
return ((Boolean)p2.isPreviouslyInQueue()).compareTo(p1.isPreviouslyInQueue());
}

关于java - 比较具有涉及 boolean 值的多个属性的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29799782/

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