Java Reference
In-Depth Information
Persons by Id:
(1, John)
(2, Adam)
(3, Eve)
(4, Donna)
Persons by Name:
(2, Adam)
(4, Donna)
(3, Eve)
(1, John)
(4, Kip)
Suppose you have a group of strings and you want to remove duplicates and sort them in ascending order of their
length. How difficult will it be to achieve this using your current knowledge of collections? The following snippet of
code shows how to do this:
// Sort the names based on their length
SortedSet<String> names = new TreeSet<>(Comparator.comparing(String::length));
names.add("Ken");
names.add("Lo");
names.add("Ellen");
names.add("Don"); // A duplicate that is ignored
// Print the sorted names
names.forEach(System.out::println);
Lo
Ken
Ellen
The
SortedSet
interface inherits all methods of the
Set
interface; it also adds some more methods to give you
access to its subsets. For example, if you want to get a subset of the
SortedSet
, you can use its
subSet(E fromElement
,
E toElement)
method to get the elements between
fromElement
(inclusive) and
toElement
(exclusive). Listing 12-11
demonstrates how to use some of the methods of the
SortedSet
interface to get a subset of its elements.
Listing 12-11.
Accessing Subsets of a SortedSet
// SortedSetSubset.java
package com.jdojo.collections;
import java.util.SortedSet;
import java.util.TreeSet;
public class SortedSetSubset {
public static void main(String[] args) {
// Create a sorted set of names
SortedSet<String> names = new TreeSet<>();
names.add("John");
names.add("Adam");
names.add("Eve");
names.add("Donna");