java - sort list of objects based on field which is can be null -
how to sort list of objects based on field can null
?
i trying in next way using comparator
interface , collections sort method. class customclass
, field on sorting done createdate
comparator comparator=new comparator<customclass>(){ public int compare(customclass o1, customclass o2) { if(o1.getcreatedate()==null && o2.getcreatedate()==null){ homecoming 0; } else if(o1.getcreatedate()==null && o2.getcreatedate()!=null){ homecoming 1; } else if(o1.getcreatedate()!=null && o2.getcreatedate()==null){ homecoming -1; } else{ if(o1.getcreatedate().equals(o2.getcreatedate())){ homecoming 0; } else if(o1.getcreatedate().after(o2.getcreatedate())){ homecoming 1; } else{ homecoming -1; } } } };
is there improve way it?
if you're willing utilize google guava, can utilize comparisonchain
, ordering
create things more succinct.
public int compare(customclass o1, customclass o2) { homecoming comparisonchain.start() .compare(o1.getcreatedate(), o2.getcreatedate(), ordering.natural().nullslast()) .result(); }
java sorting
No comments:
Post a Comment