TreeSet
The TreeSet
class in Java is an implementation of the Set
interface that stores elements in a sorted order. Elements in a TreeSet
are arranged according to their natural ordering or a specified comparator.
To use the TreeSet
class, you need to import the java.util.TreeSet
package.
Here's an example that demonstrates the usage of the TreeSet
class:
TEXT/X-JAVA
1import java.util.TreeSet;
2
3public class Main {
4
5 public static void main(String[] args) {
6 // Create a TreeSet
7 TreeSet<Integer> treeSet = new TreeSet<>();
8
9 // Adding elements to the TreeSet
10 treeSet.add(5);
11 treeSet.add(2);
12 treeSet.add(7);
13 treeSet.add(9);
14 treeSet.add(1);
15
16 // Printing the TreeSet
17 System.out.println("TreeSet: " + treeSet);
18
19 // Getting the first element
20 int firstElement = treeSet.first();
21 System.out.println("First Element: " + firstElement);
22
23 // Getting the last element
24 int lastElement = treeSet.last();
25 System.out.println("Last Element: " + lastElement);
26
27 // Checking if an element exists in the TreeSet
28 boolean contains = treeSet.contains(7);
29 System.out.println("Contains 7 in TreeSet: " + contains);
30
31 // Removing an element from the TreeSet
32 boolean removed = treeSet.remove(2);
33 System.out.println("Removed 2 from TreeSet: " + removed);
34
35 // Printing the updated TreeSet
36 System.out.println("Updated TreeSet: " + treeSet);
37
38 // Checking the size of the TreeSet
39 int size = treeSet.size();
40 System.out.println("Size of the TreeSet: " + size);
41 }
42
43}
xxxxxxxxxx
43
}
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
// Create a TreeSet
TreeSet<Integer> treeSet = new TreeSet<>();
// Adding elements to the TreeSet
treeSet.add(5);
treeSet.add(2);
treeSet.add(7);
treeSet.add(9);
treeSet.add(1);
// Printing the TreeSet
System.out.println("TreeSet: " + treeSet);
// Getting the first element
int firstElement = treeSet.first();
System.out.println("First Element: " + firstElement);
// Getting the last element
int lastElement = treeSet.last();
System.out.println("Last Element: " + lastElement);
// Checking if an element exists in the TreeSet
boolean contains = treeSet.contains(7);
System.out.println("Contains 7 in TreeSet: " + contains);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment