Beancomparator does not work with null values

My requirements are to sort the list of type Customer beans according to the property customernamein this bean ... for this I used beancomparator.it works fine when the field is customernamenot null. He throws NullPointerExceptionwhen the field null.. please help me.

my code

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...
}
+5
source share
2 answers

Pay attention to the case of validation in 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());
}
}
+1
source

I use it as follows:

    Comparator<Customer> comparator = new BeanComparator(customername, new NullComparator(false));
    if (descentSort){
        comparator = new ReverseComparator(comparator);
    }
    Collections.sort(list, comparator);

IMO is easier :)

+12
source

All Articles