我有 2 个 Java 类。一个是包含 5 个变量的 Car 类。其中我有一个List设备变量。另一个类包含 Car 类对象的列表:List carlist。
我的任务是:我必须使用 Java 中的 Streams 根据给定汽车所拥有的设备项目的数量对汽车对象列表进行排序。
我该怎么做?我试图构建一个单独的方法来计算对象列表中的项目 - 但随后在 Comparator 中我无法将对象作为此方法的参数。
这是我的代码的摘录:
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;
}
而且我尝试在 Stream 中使用这个方法:
public void sortbyEquipment (List<Car> carList){
carList.stream()
.sorted(Comparator.comparing(countEquipmentItems(Car s)));
}
}
感谢任何帮助
最佳答案
您不需要 countEquipmentItems
方法来计算设备数量。只需使用 car.getEquipment().size()
:
public void sortbyEquipment (List<Car> carList){
carList.stream()
.sorted(Comparator.comparing(car -> car.getEquipment().size()))
...
}
当然,您可以将 Comparator
直接传递给 Collections.sort()
,它将对列表进行排序而无需创建 Stream
.
关于Java <Streams> 如何根据列表组件的数量对我的对象列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49350175/