Java Reference
In-Depth Information
5
import java.util.HashSet;
6
import java.util.Set;
7
import java.util.Collection;
8
9
public class SetTest
10
{
11
public static void main(String[] args)
12
{
13
// create and display a List<String>
14
String[] colors = { "red" , "white" , "blue" , "green" , "gray" ,
15
"orange" , "tan" , "white" , "cyan" , "peach" , "gray" , "orange" };
16
List<String> list = Arrays.asList(colors);
17
System.out.printf( "List: %s%n" , list);
18
19
// eliminate duplicates then print the unique values
20
printNonDuplicates(list);
21
}
22
23
// create a Set from a Collection to eliminate duplicates
24
private static void printNonDuplicates(
Collection<String> values
)
25
{
26
// create a HashSet
27
Set<String> set = new HashSet<>(values);
28
29
System.out.printf( "%nNonduplicates are: " );
30
31
for (String value : set)
32
System.out.printf( "%s " , value);
33
34
System.out.println();
35
}
36
} // end class SetTest
List: [red, white, blue, green, gray, orange, tan, white, cyan, peach, gray,
orange]
Nonduplicates are: orange green white peach gray cyan red blue tan
Fig. 16.16 | HashSet used to remove duplicate values from an array of strings. (Part 2 of 2.)
Sorted Sets
The collections framework also includes the SortedSet interface (which extends Set ) for
sets that maintain their elements in sorted order—either the elements' natural order (e.g.,
numbers are in ascending order) or an order specified by a Comparator . Class TreeSet im-
plements SortedSet . The program in Fig. 16.17 places String s into a TreeSet . The
String s are sorted as they're added to the TreeSet . This example also demonstrates range-
view methods, which enable a program to view a portion of a collection.
Line 14 creates a TreeSet<String> that contains the elements of array colors , then
assigns the new TreeSet<String> to SortedSet<String> variable tree . Line 17 outputs
the initial set of strings using method printSet (lines 33-39), which we discuss momen-
tarily. Line 31 calls TreeSet method headSet to get a subset of the TreeSet in which every
 
Search WWH ::




Custom Search