My requirements is to sort list of Customer type beans according to customername
property in that bean... for that i used beancomparator
.it is working fine when customername
field is not null
.
It is throwing NullPointerException
when the field is null
..please help me out..
my code is
public class customer{
private String customername;
}
main()
{
list<customer> list=new arraylist();
//list is filled with customertype beans
comparator<customer> comp=new beancomparator(customername);
collections.sort(list,comp);//throwing error when customername is null...
}
I use it this way:
Comparator<Customer> comparator = new BeanComparator(customername, new NullComparator(false));
if (descentSort){
comparator = new ReverseComparator(comparator);
}
Collections.sort(list, comparator);
IMO it is easier way :)
Handle the case of nullity check in your Comparator
new Comparator<Customer>() {
public int compare(Customer o1, Customer o2) {
if(o1.getName() == null){ return -1;}
if(o2.getName() == null){ return 1;}
return o1.getName().compareTo(o2.getName());
}
}
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