I have a string arraylist with some null
values and some strings. I don't want to sort the arraylist but I should sort the arraylist such that null values comes last. Lets say arraylist is {1,2,null,6,5,null, 3}
, I should get null values last {1,2,6,5,3,null,null}
.
Solution , I currently have:
Right now, I am constructing new arraylist and If the value is null
, I am not pushing it to new list otherwise I am adding it to new arraylist.
Any other better solution?
Thanks for the help.
If you are using Java 8, you can easily build the comparator you need:
Arrays.sort(stringArray, Comparator.nullsLast(Comparator.naturalOrder()));
But if you not using java 8 you can have a comparator like below
public class StringNullComparator implements Comparator<String> {
public int compare(String stringOne, String stringTwo) {
if (stringOne != null && stringTwo != null)
return stringOne.compareTo(stringTwo);
return (stringOne == stringTwo)?0:(stringOne==null? 1 : -1);
}
}
And you can use at stated below
Arrays.sort(stringArray, new StringNullComparator());
Custom Comparator to pass to sort:
public class StringComparator implements Comparator<String> {
public int compare(String s1, String s2) {
if (s1 != null && s2 != null)
return s1.compareTo(s2);
return (s1 == null) ? 1 : -1;
}
}
then:
Collectios.sort(list, new StringComparator());
If you want to avoid explicitly iterating over the whole list you could use ArrayList.indexOf() to find the null values, then remove() them. If you want to keep the values in the list you can then just add a null value to the end of the list. However I would imagine this approach is not great in terms of performance if this is a concern.
You can use NullComparator from apache.
Collections.sort(list, new NullComparator());
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