First of all, I've already looked at the many questions and answers about this exception but most of them are just about comparing simple integers or the same properties.
What I have is an object that has two dates, that when one is null I will use the other one to compare, ex of the class:
public class MyClass {
private LocalDate primaryDate;
private LocalDate secondaryDate;
private String Code;
}
the comparison method is:
private List<MyClass> sortByDates(final List<MyClass> listOfClass) {
Comparator<MyClass> comparator = ((Comparator<MyClass>) (first, second) -> {
if (first.getPrimaryDate() == null || second.getPrimaryDate() == null) {
return first.getSecondaryDate().compareTo(second.getSecondaryDate());
}
return first.getPrimaryDate().compareTo(second.getPrimaryDate());
}).reversed().thenComparing(MyClass::getCodeAsLong);
return listOfClass.stream()
.sorted(comparator)
.collect(Collectors.toList());
}
Obs1: secondaryDate
is never null but I have to use the primaryDate
as first option to compare, and primaryDate
is never less than secondaryDate
Obs2: Code
property is saved as a string but don't have any letter, so it can be converted to long
question from:
https://stackoverflow.com/questions/65936878/exception-comparison-method-violates-its-general-contract-when-comparing-two 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…