Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort list of objects based on field which can be null

Tags:

java

null

sorting

How to to sort list of objects based on field which can be null?

I am trying to do it in following way using Comparator interface and collections sort method. The class is CustomClass and the field on which sorting is to be done is createDate

Comparator comparator=new Comparator<CustomClass>(){
        public int compare(CustomClass o1, CustomClass o2) {
            if(o1.getCreateDate()==null && o2.getCreateDate()==null){
                return 0;
            }
            else if(o1.getCreateDate()==null && o2.getCreateDate()!=null){
                return 1;
            }
            else if(o1.getCreateDate()!=null && o2.getCreateDate()==null){
                return -1;
            }
            else{
                if(o1.getCreateDate().equals(o2.getCreateDate())){
                    return 0;   
                }
                else if(o1.getCreateDate().after(o2.getCreateDate())){
                    return 1;   
                }
                else{
                    return -1;
                }
            }                       
        }
    };

Is there a better way to do it?

like image 523
Orchid Avatar asked Dec 19 '22 09:12

Orchid


1 Answers

If you're willing to use Google Guava, then you can use ComparisonChain and Ordering to make things more succinct.

public int compare(CustomClass o1, CustomClass o2)
{
  return ComparisonChain.start()
    .compare(o1.getCreateDate(), o2.getCreateDate(), Ordering.natural().nullsLast())
    .result();
}
like image 87
Greg Kopff Avatar answered Dec 22 '22 00:12

Greg Kopff