Sub topic 3
Handling Nulls and Choosing an Ordering
Assume you know Java classes, generics, collections, equals, and basic Comparator usage. A comparator defines whether one value is less than, equal to, or greater than another. A null value has no methods or natural ordering, so comparing it directly with a non-null value can throw NullPointerException.
Handling Nulls with `nullsFirst` and `nullsLast`
Wrap an existing comparator with Comparator.nullsFirst or Comparator.nullsLast. The wrapper decides where null belongs, then delegates non-null comparisons.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = Arrays.asList("b", null, "a");
words.sort(Comparator.nullsFirst(Comparator.naturalOrder()));
System.out.println(words); // [null, a, b]
words.sort(Comparator.nullsLast(Comparator.naturalOrder()));
System.out.println(words); // [a, b, null]
}
}Use nullsFirst when missing values should appear before real values. Use nullsLast when they should appear at the end.
Sorted Collections
TreeSet, TreeMap, and PriorityQueue use an ordering to position elements. They use either Comparable or a supplied Comparator.
A TreeSet treats two values as duplicates when their comparison returns zero. A TreeMap treats keys the same way. A PriorityQueue uses the ordering to identify the next element, but it does not fully sort iteration.
Consistency with `equals`
Ideally, compareTo or compare returns zero exactly when equals returns true. Otherwise, a sorted collection can disagree with a HashSet.
BigDecimal is a known exception: 1.0 and 1.00 compare as equal, but equals considers their scales different. A TreeSet<BigDecimal> therefore stores only one of them.
Common Pitfalls
Never compare numbers by subtraction. Overflow can reverse the result.
Comparator<Integer> safe = Integer::compare;Also avoid comparators that change their result while an element is inside a TreeSet, TreeMap, or PriorityQueue. Mutable fields used for ordering can make the collection's internal structure incorrect.
Choosing an Approach
Implement Comparable when the class has one clear, widely useful natural ordering. Use Comparator when callers need different orderings, when the class cannot be changed, or when the ordering belongs to a particular operation.
Exercise
Which wrapper sorts null values after non-null strings?
Show answer
Comparator.nullsLast(Comparator.naturalOrder()).