Java Reference
In-Depth Information
a portion of the set whose elements are less than
toElement
and greater than or equal to
fromElement
, respectively.
NavigableSet
extends
SortedSet
to provide navigation methods
lower(e)
,
floor(e)
,
ceiling(e)
, and
higher(e)
that return elements respectively less than, less
than or equal, greater than or equal, and greater than a given element and return
null
if there
is no such element. The
pollFirst()
and
pollLast()
methods remove and return the first
and last element in the tree set, respectively.
TreeSet
implements the
SortedSet
interface. To create a
TreeSet
, use a constructor,
as shown in Figure 21.1. You can add objects into a
tree set
as long as they can be compared
with each other.
As discussed in Section 20.5, the elements can be compared in two ways: using the
Comparable
interface or the
Comparator
interface.
Listing 21.4 gives an example of ordering elements using the
Comparable
interface. The
preceding example in Listing 21.3 displays all the strings in their insertion order. This example
rewrites the preceding example to display the strings in alphabetical order using the
TreeSet
class.
tree set
L
ISTING
21.4
TestTreeSet.java
1
import
java.util.*;
2
3
public class
TestTreeSet {
4
public static void
main(String[] args) {
5
// Create a hash set
6
Set<String> set =
new
HashSet<>();
create hash set
7
8
// Add strings to the set
9 set.add(
"London"
);
10 set.add(
"Paris"
);
11 set.add(
"New York"
);
12 set.add(
"San Francisco"
);
13 set.add(
"Beijing"
);
14 set.add(
"New York"
);
15
16 TreeSet<String> treeSet =
new
TreeSet<>(set);
17 System.out.println(
"Sorted tree set: "
+ treeSet);
18
19
// Use the methods in SortedSet interface
20 System.out.println(
"first(): "
+ treeSet.first());
21 System.out.println(
"last(): "
+ treeSet.last());
22 System.out.println(
"headSet(\"New York\"): "
+
23 treeSet.headSet(
"New York"
));
24 System.out.println(
"tailSet(\"New York\"): "
+
25 treeSet.tailSet(
"New York"
));
26
27
// Use the methods in NavigableSet interface
28 System.out.println(
"lower(\"P\"): "
+ treeSet.lower(
"P"
));
29 System.out.println(
"higher(\"P\"): "
+ treeSet.higher(
"P"
));
30 System.out.println(
"floor(\"P\"): "
+ treeSet.floor(
"P"
));
31 System.out.println(
"ceiling(\"P\"): "
+ treeSet.ceiling(
"P"
));
32 System.out.println(
"pollFirst(): "
+ treeSet.pollFirst());
33 System.out.println(
"pollLast(): "
+ treeSet.pollLast());
34 System.out.println(
"New tree set: "
+ treeSet);
35 }
36 }
create tree set
display elements
Sorted tree set: [Beijing, London, New York, Paris, San Francisco]
first(): Beijing
last(): San Francisco
Search WWH ::
Custom Search