gpt4 book ai didi

java - 基于java中的嵌套值对对象列表进行排序

转载 作者:行者123 更新时间:2023-12-02 09:14:34 25 4
gpt4 key购买 nike

I have a list of Cars scheduled for delivery for multiple dates which needs to be sorted on the basis of the below points:

  • 如果isReady>0,那么它应该首先显示在表格中。和那么该特定日期的其他值就会低于它。
  • 如果isReady>0并且对象gear!=null那么,它首先显示在该特定日期的表。后面跟着其他值,其中 Object gear==null
  • 如果 isReady>0、对象 gear!=null 和对象 tyre!=null,则该特定日期的值首先显示在表中。接下来是其他值,其中对象 gear==nulltyre==null

以下是代码:

public class Car {
private int isReady;
private Tyre tyre;
private Gear gear;
private Date deliveryDate;
}


public class Gear {
private int id;
private String type;
}


public class Tyre {
private int id;
private String grip;
}

public class CarComparator implements Comparator<Car> {
@Override
public int compare(Car entry1, Car entry2) {
int value = 0;

if (entry1.getIsReady() > entry2.getIsReady()) {
value = -1;
} else if (entry1.getIsReady() < entry2.getIsReady()) {
value = 1;
} else if (entry1.getIsReady() == entry2.getIsReady()) {
value = 0;
}
return value;
}
}

I have developed a Comparator which works fine for the first condition where isReady>0. Could you please help me with the other conditions mentioned above.

提前致谢。

最佳答案

好吧,从 Java 8 开始,您可以像这样构建比较器:

//order by delivery date first, ascending order
Comparator<Car> carComparator = Comparator.comparing( Car::getDeliveryDate )
//order by isReady in ascending order
.thenComparing( Car::getIsReady )
//we map null to 1 and non-null to -1 and ignore the rest for now
.thenComparing( car -> car.getGear() != null ? -1 : 1 )
.thenComparing( car -> car.getTyre() != null ? -1 : 1 );

关于java - 基于java中的嵌套值对对象列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58317043/

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