I want to develop a sorting demo for car list. I am using data table to display car list. Now actually I want to sort the list by car color. Here it is not sort by alphabetic order. I want to use my custom sorting order like Red car come first, then Blue, etc.
For that I try to use Java Comparator
and Comparable
but it allows to sort in alphabetic order only.
So, can any one guide me the way to implement the technique to use so that the sorting becomes faster.
class Car implements Comparable<Car>
{
private String name;
private String color;
public Car(String name, String color){
this.name = name;
this.color = color;
}
//Implement the natural order for this class
public int compareTo(Car c) {
return name.compareTo(c.name);
}
static class ColorComparator implements Comparator<Car> {
public int compare(Car c1, Car c2) {
String a1 = c1.color;
String a2 = c2.color;
return a1.compareTo(a2);
}
}
public static void main(String[] args) {
List<Car> carList = new ArrayList<>();
List<String> sortOrder = new ArrayList<>();
carList.add(new Car("Ford","Silver"));
carList.add(new Car("Tes","Blue"));
carList.add(new Car("Honda","Magenta"));
sortOrder.add("Silver");
sortOrder.add("Magenta");
sortOrder.add("Blue");
// Now here I am confuse how to implement my custom sort
}
}
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…