почему бы не использовать Integer.compareTo, чтобы сделать код короче?
примерно так:
import java.util.Comparator;
public class CarComparator implements Comparator<Car> {
@Override
public int compare(Car entry1, Car entry2) {
int value = 0;
// might want to add a null check for either entry1 and entry2
value = entry1.getDeliveryDate().compareTo(entry2.getDeliveryDate());
if (value == 0) {
value = ((Integer)entry1.getIsReady()).compareTo((Integer)entry2.getIsReady());
if (value == 0) {
value = getIntegerValueForNullCheck(entry1.getGear()).compareTo(getIntegerValueForNullCheck(entry2.getGear()));
if (value == 0) {
value = getIntegerValueForNullCheck(entry1.getTyre()).compareTo(getIntegerValueForNullCheck(entry2.getTyre()));
}
}
}
return value;
}
private Integer getIntegerValueForNullCheck (Object o) {
return o == null ? 0 : 1;
}
}
включая код, который проверяет сортировку:
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.*;
public class Sorting {
public static void main(String[] args) {
List<Car> cars = new LinkedList<>();
Date today = new Date();
Instant now = Instant.now();
Instant after = now.plus(Duration.ofDays(1));
Date tomorrow = Date.from(after);
cars.add(new Car(5, new Tyre(1,"1"), new Gear(1, "1"), today ));
cars.add(new Car(5, new Tyre(1,"1"), null, today ));
cars.add(new Car(5, null, null, today ));
cars.add(new Car(4, null, null, today ));
cars.add(new Car(3, null, null, tomorrow ));
Collections.sort(cars, new CarComparator());
System.out.println(cars);
}
}
вывод:
[Car{isReady=4, tyre=null, gear=null, deliveryDate=Thu Oct 10 11:27:20 IDT 2019}
, Car{isReady=5, tyre=null, gear=null, deliveryDate=Thu Oct 10 11:27:20 IDT 2019}
, Car{isReady=5, tyre=Tyre{id=1, grip='1'}, gear=null, deliveryDate=Thu Oct 10 11:27:20 IDT 2019}
, Car{isReady=5, tyre=Tyre{id=1, grip='1'}, gear=Gear{id=1, type='1'}, deliveryDate=Thu Oct 10 11:27:20 IDT 2019}
, Car{isReady=3, tyre=null, gear=null, deliveryDate=Fri Oct 11 11:27:20 IDT 2019}
]