I have a list of Cars scheduled for delivery for multiple dates which needs to be sorted on the basis of the below points:
- If
isReady>0,then it should be displayed first in the table. And then the other values come below it for that particular date. - If
isReady>0and Objectgear!=nullthen, it is displayed first in the table for that particular date. Followed by the other values where Objectgear==null. - If
isReady>0, Objectgear!=nulland Objecttyre!=null, then that value is displayed first in the table for that particular date. Followed by the other values where Objectgear==nullandtyre==null.
Here are the class codes:
public class Car {
private int isReady;
private Tyre tyre;
private Gear gear;
private Date deliveryDate;
}
public class Gear {
private int id;
private String type;
}
public class Tyre {
private int id;
private String grip;
}
public class CarComparator implements Comparator<Car> {
@Override
public int compare(Car entry1, Car entry2) {
int value = 0;
if (entry1.getIsReady() > entry2.getIsReady()) {
value = -1;
} else if (entry1.getIsReady() < entry2.getIsReady()) {
value = 1;
} else if (entry1.getIsReady() == entry2.getIsReady()) {
value = 0;
}
return value;
}
}
I have developed a Comparator which works fine for the first condition where
isReady>0. Could you please help me with the other conditions mentioned above.
Thanks in advance.
valueis not0at the end, you can return it. But if it is0, you need to then compare the next condition. And so on.int value =Integer.compare(entry2.getIsReady(), entry1.getIsReady() );.0and you still have something to compare, you need to do more comparisons.isReady>0doesn't match your comparator. To clarify: you have all cars in a list and want to sort them 1) by date in ascending order, 2) byisReadyin ascending order, 3) non-null values first forgearand 4) non-null values first fortyre- is that correct? How should cars with the same date,isReadyagearand atyrebe sorted? Does it matter?