Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java <Streams> How to sort the list of my objects, based on the count of the components of the List

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

like image 936
Przemek Avatar asked Mar 18 '18 16:03

Przemek


People also ask

How do you sort a list of objects based on value?

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.

How do you sort a list of objects based on an attribute of the objects in Java 8?

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.

Can we sort list of objects in Java?

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.


1 Answers

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.

like image 116
Eran Avatar answered Oct 03 '22 19:10

Eran