Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an object based on time and avoiding explicit NULL checks

Tags:

java

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());
        }
    });
like image 945
pjj Avatar asked Mar 10 '26 03:03

pjj


1 Answers

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();
    }
}
like image 76
JustinKSU Avatar answered Mar 12 '26 17:03

JustinKSU