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.
To sort on natural order, after ordering null values, use Comparator. nullsFirst( Comparator. naturalOrder() ).
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.
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.
How about this:
roleList.sort(Comparator.comparing(Role::getRoleName,
Comparator.nullsLast(Comparator.comparing(String::trim))));
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