Java Reference
In-Depth Information
element is less than
"orange"
. The view returned from
headSet
is then output with
printSet
. If any changes are made to the subset, they'll
also
be made to the original
TreeSet
, because the subset returned by
headSet
is a view of the
TreeSet
.
Line 25 calls
TreeSet
method
tailSet
to get a subset in which each element is greater
than or equal to
"orange",
then outputs the result. Any changes made through the
tailSet
view are made to the original
TreeSet
. Lines 28-29 call
SortedSet
methods
first
and
last
to get the smallest and largest elements of the set, respectively.
Method
printSet
(lines 33-39) accepts a
SortedSet
as an argument and prints it.
Lines 35-36 print each element of the
SortedSet
using the enhanced
for
statement.
1
// Fig. 16.17: SortedSetTest.java
2
// Using SortedSets and TreeSets.
3
import
java.util.Arrays;
4
import
java.util.SortedSet;
5
import
java.util.TreeSet;
6
7
public class
SortedSetTest
8
{
9
public static void
main(String[] args)
10
{
11
// create TreeSet from array colors
12
String[] colors = {
"yellow"
,
"green"
,
"black"
,
"tan"
,
"grey"
,
13
"white"
,
"orange"
,
"red"
,
"green"
};
14
SortedSet<String> tree =
new
TreeSet<>(Arrays.asList(colors));
15
16
System.out.print(
"sorted set: ")
;
17
printSet(tree);
18
19
// get headSet based on "orange"
20
System.out.print(
"headSet (\"orange\"): "
);
21
printSet(
tree.headSet(
"orange"
)
);
22
23
// get tailSet based upon "orange"
24
System.out.print(
"tailSet (\"orange\"): "
);
25
printSet(
tree.tailSet(
"orange")
);
26
27
// get first and last elements
28
System.out.printf(
"first: %s%n"
,
tree.first()
tree.last()
);
29
System.out.printf(
"last : %s%n"
,
);
30
}
31
32
// output SortedSet using enhanced for statement
33
private static void
printSet(SortedSet<String> set)
34
{
35
for
(String s : set)
36
System.out.printf(
"%s "
, s);
37
38
System.out.println();
39
}
40
}
// end class SortedSetTest
Fig. 16.17
|
Using
SortedSet
s and
TreeSet
s. (Part 1 of 2.)