I'm getting a NullPointerException
when i try to sort a list with by doing the Collections.sort(list2)
the list contains the following strings
[BOOTH 4, ENP ROOM, BOOTH 6, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, BOOTH 10, BOOTH 7, BOOTH 3, BOOTH 1, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, BOOTH 1, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, BOOTH 10, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]
Do i need to use comparator for this list?
You could use a comparator that can handle null values. Eg
private static final class NullsFirstComparator implements Comparator<String> {
public int compare(String lhs, String rhs) {
if (lhs == rhs)
return 0;
if (lhs == null)
return -1;
if (rhs == null)
return 1;
return lhs.compareTo(rhs);
}
}
Which will sort the null values first (they are less than everything)
Remove null
values before sorting. They can't be sorted
You can also use NullComparator
in Apache commons. It provide lot of useful utilities for writing comparator
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.