Qais Qais - 4 months ago 7
Java Question

Sort objects of a list in java

consider this the Car class:

class Car {
String name;
String company;
}


i want to add the cars into a list, but i want the cars with the same company name to be ordered after each other in the list. so if we have :

-Toyota : Camry, Corolla, Yaris, Hilux

-Ford : Mustang, Fusion

-Nissan : Sentra, Altima, Pathfinder

the list ordering should be:

{Camry, Corolla, Yaris, Hilux, Mustang, Fusion, Sentra, Altima, Pathfinder}


and i want the cars with the company name that comes first in alphabetical order to be put first in the list. So in case of Toyota, Ford and Nissan the first cars to enter the list should be the ones with Ford then Nissan then Toyota. So the list will be:

`{Mustang, Fusion, Sentra, Altima, Pathfinder, Camry, Corolla, Yaris, Hilux}`


what is the best way to do so in java?

Answer

use an anonymous comparator when calling the Collections.sort()

Example:

List<Car> myCars = new ArrayList<>();
Collections.sort(myCars, new Comparator<Car>() {
    @Override
    public int compare(Car o1, Car o2) {
    return o1.getCompany().compareTo(o2.getCompany());
    }
});