Java <Streams> How to sort a list of my objects based on counting list components
I have 2 classes in Java. One of them is the Car class, which consists of 5 variables. Among them, I have a List List variable. Another class contains a list of objects of the Car class: List carlist.
My task: I need to sort the list of car objects using Streams in Java, based on the number of pieces of equipment that this car has.
How should I do it? I tried to create a separate method for counting the elements in the list of the object, but then inside the Comparator I can not put the object as an argument to this method.
Here is an excerpt of my code:
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;
}
And I tried using this method in a thread:
public void sortbyEquipment (List<Car> carList){
carList.stream()
.sorted(Comparator.comparing(countEquipmentItems(Car s)));
}
}
I appreciate any help
+4
2