我有两个Java类。一个是由5个变量组成的汽车类。其中我有一个设备列表变量。另一个类包含Car类对象的列表: list carlist。
我的任务是:使用Java中的流,根据给定汽车拥有的设备项目数量,对car对象列表进行排序。
我该怎么做?我试图构建一个单独的方法来计算对象列表中的项,但是在比较器中,我不能将对象作为该方法的参数。
下面是我代码的摘录:
private int countEquipmentItems (Car s){
if (s == null){
return 0;
}
int countEquipment = 0;
List<String> a = s.getEquipment();
for (int i = 0; i <a.size() ; i++) {
countEquipment ++;
}
return countEquipment;
}我尝试在流中使用这个方法:
public void sortbyEquipment (List<Car> carList){
carList.stream()
.sorted(Comparator.comparing(countEquipmentItems(Car s)));
}
}我很感谢你的帮助
发布于 2018-03-18 16:29:04
您不需要使用countEquipmentItems方法来计算设备的数量。只需使用car.getEquipment().size()
public void sortbyEquipment (List<Car> carList){
carList.stream()
.sorted(Comparator.comparing(car -> car.getEquipment().size()))
...
}当然,您可以将该Comparator直接传递给Collections.sort(),后者将对列表进行排序,而不必创建Stream。
发布于 2018-03-18 21:51:30
您的countEquipmentItems方法是多余的,完全没有必要。
Eran提供的另一个解决方案是调用对sort类型可用的默认List<T>方法。
carList.sort(Comparator.comparingInt(car -> car.getEquipment().size()));或者,如果希望排序的项位于新集合中,则可以:
List<Car> clonedList = new ArrayList<>(carList); // clone the carList
clonedList.sort(Comparator.comparingInt(car -> car.getEquipment().size()));https://stackoverflow.com/questions/49350175
复制相似问题