I am trying to sort a POJO based on time. I figured out that there are possibilities for NPE so I have placed appropriate NULL checks.
But I want to know if there is any Java primitive method in J2SE or some other library such that I can avoid explicit NULL checks. I know there are many such good method in org.apache.commons.lang3.StringUtils but none suffice my requirement.
In below code ABC.getCal() returns a Calendar object.
Collections.sort(abcList, new Comparator<ABC>() {
@Override
public int compare(ABC o1, ABC o2) {
if (a1 == null || a2 == null)
return 0;
return a1.getCal.compareTo(a2.getCal());
}
});
CompareToBuilder is a great way to compare two objects. It is null safe and makes the code clean.
For example:
public class MyClass implements Comparable<MyClass> {
private String cal;
public String getCal() {
return cal;
}
public void setCal(String cal) {
this.cal = cal;
}
@Override
public int compareTo(MyClass o) {
return new CompareToBuilder().append(this.cal, o.getCal()).toComparison();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With