Instead of worrying about the null values in your set, think of it like this:
- If you're comparing against one non-null value and one null value, the non-null value wins.
- If you're comparing against two non-null values, neither wins.
You can create a custom Comparator<String>, and use it in Arrays#sort. As an aside, String.CASE_INSENSITIVE_ORDER is also a Comparator<String>, but it doesn't quite fill the need that you seem to have.
Here's an example implementation:
public class NullAwareStringComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
if (o1 == null && o2 == null) {
return 2;
} else if (o1 == null) {
return 1;
} else if (o2 == null) {
return -1;
} else {
return o1.compareToIgnoreCase(o2);
}
}
}
You would then call your sort method with it as such:
Arrays.sort(words, new NullAwareStringComparator());
This puts all of the null values at the end of the array. If you want the reverse ordering, flip the sign of the numbers returned in the compare method.
Alternatively, if you don't know/care how many elements you can hold, consider using a TreeSet<String> instead - this has the added benefit of ignoring duplicate entries.
Set<String> sortedStrings = new TreeSet<>(new NullAwareStringComparator());
You could also use String.CASE_INSENSITIVE_ORDER as the comparator instead, since at this point, you're not nearly as worried about null entries as you previously were:
Set<String> sortedStrings = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
...and to sort the collection, you would call Collections.sort().
ArrayListif you are not sure of thesize. don't hardcode it