I have 2 classes in Java. One is a Car class that consists of 5 variables. Among them I have a List equipment variable. Another class contains the list of the Car class objects: List carlist.
My task is: I have to sort the list of car object, using Streams in Java based on the amount of the equipment items that the given car have.
How do I do that? I tried to build a separate method to count the items on the list of the object - but then within the Comparator I can't place an Object as an argument of this method.
Here's 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 have tried to use this method within the Stream:
public void sortbyEquipment (List<Car> carList){
carList.stream()
.sorted(Comparator.comparing(countEquipmentItems(Car s)));
}
}
I appreciate any help
In the main() method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.
Java 8 introduced a sort method in the List interface which can use a comparator. The Comparator. comparing() method accepts a method reference which serves as the basis of the comparison. So we pass User::getCreatedOn to sort by the createdOn field.
Here we will learn how to sort a list of Objects in Java. We can use Collections. sort() method to sort a list in the natural ascending order. All the elements in the list must implement Comparable interface, otherwise IllegalArgumentException is thrown.
You don't need that countEquipmentItems
method to count the amount of equipment. Just use car.getEquipment().size()
:
public void sortbyEquipment (List<Car> carList){
carList.stream()
.sorted(Comparator.comparing(car -> car.getEquipment().size()))
...
}
Of course, you can pass that Comparator
directly to Collections.sort()
, which will sort the list without having to create a Stream
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With