I have a class
LoanAccount
that contains an attributescreationDate
andloanAmount
.I want to implement a Comparator that sorts the accounts by loan amount in descending order. When the loan amounts are the same, sorts the accounts ascending by date.
The code look like this:
Class
public class LoanAccount {
private String id;
private Date creationDate;
private BigDecimal loanAmount;
}
Comparator
public class LoanAccountAmountComparator implements Comparator<LoanAccount> {
@Override
public int compare(LoanAccount o1, LoanAccount o2) {
if (o1 == null) {
if (o2 == null) {
return 0;
}
return -1;
}
if (o2 == null) {
return 1;
}
if (o1.getLoanAmount() == null) {
if (o2.getLoanAmount() == null) {
return 0;
}
return -1;
}
if (o2.getLoanAmount() == null) {
return 1;
}
int comparedLoanAmount = o2.getLoanAmount().compareTo(o1.getLoanAmount());
if (comparedLoanAmount == 0) {
if (o1.getCreationDate() == null) {
if (o2.getCreationDate() == null) {
return 0;
}
return -1;
}
if (o2.getCreationDate() == null) {
return 1;
}
return o1.getCreationDate().compareTo(o2.getCreationDate());
} else {
return comparedLoanAmount;
}
}
}
Objects o1
, o2
can be null. Fields creationDate
and loanAmount
can be null.
I want to ask you if there are better ways to handle null pointer exception in compareTo method.
For me it looks like there are too many if conditions