Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beancomparator not working with null values

Tags:

java

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...
}
like image 878
Kiran Babu Avatar asked Jan 28 '13 18:01

Kiran Babu


2 Answers

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 :)

like image 167
Saram Avatar answered Sep 20 '22 02:09

Saram


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());
}
}
like image 20
jmj Avatar answered Sep 23 '22 02:09

jmj