A Set is an unordered Collection
of unique elements (i.e., no duplicate elements). The collections framework contains several Set
implementations, including HashSet and TreeSet. HashSet
stores its elements in a hash table, and TreeSet
stores its elements in a tree. Hash tables are presented in Section J.9.
Figure J.8 uses a HashSet
to remove duplicate strings from a List
. Recall that both List
and Collection
are generic types, so line 16 creates a List
that contains String
objects, and line 20 passes a Collection
of String
s to method printNonDuplicates
.
1 // Fig. J.8: SetTest.java
2 // HashSet used to remove duplicate values from an array of strings.
3 import java.util.List;
4 import java.util.Arrays;
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
", list );
18
19 // eliminate duplicates then print the unique values
20 printNonDuplicates( list );
21 } // end main
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< String >( values );
28
29 System.out.print( "
Nonduplicates are: " );
30
31 for ( String value : set )
32 System.out.printf( "%s ", value );
33
34 System.out.println();
35 } // end method printNonDuplicates
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
Method printNonDuplicates
(lines 24–35) takes a Collection
argument. Line 27 constructs a HashSet<String>
from the Collection<String>
argument. By definition, Set
s do not contain duplicates, so when the HashSet
is constructed, it removes any duplicates in the Collection
. Lines 31–32 output elements in the Set
.