Java Reference
In-Depth Information
// Print the sorted set
System.out.println("Sorted Set: " + names);
// Print the first and last elements in the sorted set
System.out.println("First: " + names.first());
System.out.println("Last: " + names.last());
SortedSet ssBeforeDonna = names.headSet("Donna");
System.out.println("Head Set Before Donna: " + ssBeforeDonna);
SortedSet ssBetwenDonnaAndJohn = names.subSet("Donna", "John");
System.out.println("Subset between Donna and John (exclusive): " +
ssBetwenDonnaAndJohn);
// Note the trick "John" + "\0" to include "John" in the subset
SortedSet ssBetwenDonnaAndJohn2 = names.subSet("Donna", "John" + "\0");
System.out.println("Subset between Donna and John (Inclusive): " +
ssBetwenDonnaAndJohn2);
SortedSet ssDonnaAndAfter = names.tailSet("Donna");
System.out.println("Subset from Donna onwards: " + ssDonnaAndAfter);
}
}
Sorted Set: [Adam, Donna, Eve, John]
First: Adam
Last: John
Head Set Before Donna: [Adam]
Subset between Donna and John (exclusive): [Donna, Eve]
Subset between Donna and John (Inclusive): [Donna, Eve, John]
Subset from Donna onwards: [Donna, Eve, John]
How is a null element stored in a SortedSet ? If a SortedSet uses natural order (uses the Comparable interface's
compareTo() method), adding a null element will throw a NullPointerException . If you use a Comparator object
to apply the ordering, it is up to you to allow a null element in the SortedSet . If you allow a null element in the
SortedSet , you can decide whether the null element will be placed in the beginning or at the end of the Set . The
following snippet of code creates a SortedSet using a Comparator that places the null element first:
// Sort the names based on their length, placing null first
SortedSet<String> names =
new TreeSet<>(Comparator.nullsFirst(Comparator.comparing(String::length)));
names.add("Ken");
names.add("Lo");
names.add("Ellen");
names.add(null); // Adds a null
// Print the names
names.forEach(System.out::println);
 
Search WWH ::




Custom Search