I am using java 8. I have a list of car objects . I want to sort them in a specific order.
each car objects belong to a model . i like to sort the list of car objects by model. The sorted list should be in the following order , cars with models SEDAN, then followed by BMW and then UNICORN.
import java.util.ArrayList;
import java.util.List;
enum Model {
BMW, SEDAN, UNICORN
}
public class Car {
private Model model;
private int id;
public Car(Model model, int id) {
super();
this.model = model;
this.id = id;
}
public Model getModel() {
return model;
}
public void setModel(Model model) {
this.model = model;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public static void main(String[] args) {
List<Car> l = new ArrayList<Car>();
Car c1 = new Car(Model.BMW, 1);
Car c2 = new Car(Model.BMW, 2);
Car c3 = new Car(Model.SEDAN, 3);
Car c4 = new Car(Model.SEDAN, 4);
Car c5 = new Car(Model.SEDAN, 5);
Car c6 = new Car(Model.UNICORN, 6);
Car c7 = new Car(Model.BMW, 7);
Car c8 = new Car(Model.BMW, 8);
l.add(c1);
l.add(c2);
l.add(c3);
l.add(c4);
l.add(c5);
l.add(c6);
l.add(c7);
l.add(c8);
}
}
so when i print the sorted list it should be like this
[Car [model=SEDAN, id=3], Car [model=SEDAN, id=4] ,Car [model=SEDAN, id=5], [model=BMW, id=1], Car [model=BMW, id=2], Car [model=BMW, id=7], Car [model=BMW, id=8], Car [model=UNICORN, id=6]]
How can i achieve this order of sorting on the model enum with a custom comparator.
appreciate if you can help