Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use trim and avoid NPE by using collections.sort?

There is a Class Role, having data member as String roleName. I have to sort a list of Role. While sorting I need to check NPE and trim roleName also. So I used

roleList.sort(Comparator.comparing(Role::getRoleName, 
    Comparator.nullsLast(Comparator.naturalOrder())));

I can suppress the null pointer exception but can't use trim.

roleList.sort( (x, y) -> x.getRole().trim().compareTo(y.getRole().trim()));

Using this I can't avoid NPE.

like image 879
Sheshanath Kumar Avatar asked Jun 24 '20 04:06

Sheshanath Kumar


People also ask

How to sort null values in Java?

To sort on natural order, after ordering null values, use Comparator. nullsFirst( Comparator. naturalOrder() ).

How do you sort objects in collections?

Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.

How do I sort using Comparator?

Method 2: Using comparator interface- Comparator interface is used to order the objects of a user-defined class. This interface is present in java. util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort the elements based on data members.


1 Answers

How about this:

roleList.sort(Comparator.comparing(Role::getRoleName,
    Comparator.nullsLast(Comparator.comparing(String::trim))));
like image 97
ZhekaKozlov Avatar answered Oct 03 '22 14:10

ZhekaKozlov