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?
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();
}
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