The TreeSet and TreeMap classes are important implementations of the Set and Map interfaces in the Java Collections Framework. These classes provide ordered collection and mapping functionality.
TreeSet: The TreeSet class implements the Set interface and uses a self-balancing binary search tree called a Red-Black tree
. This tree structure allows the elements to be stored in sorted order based on their natural ordering or a custom comparator.
Here's an example of using the TreeSet class:
1import java.util.TreeSet;
2
3public class Main {
4 public static void main(String[] args) {
5 // Creating a TreeSet
6 TreeSet<Integer> numbers = new TreeSet<>();
7
8 // Adding elements to the TreeSet
9 numbers.add(5);
10 numbers.add(2);
11 numbers.add(8);
12
13 // Printing the elements in sorted order
14 for (int number : numbers) {
15 System.out.println(number);
16 }
17 }
18}
The output of the above code will be:
12
25
38
TreeMap: The TreeMap class implements the Map interface and uses a Red-Black tree
to store the key-value pairs. Similar to TreeSet, TreeMap also maintains the elements in sorted order based on their keys' natural ordering or a custom comparator.
Here's an example of using the TreeMap class:
1import java.util.TreeMap;
2
3public class Main {
4 public static void main(String[] args) {
5 // Creating a TreeMap
6 TreeMap<String, Integer> studentScores = new TreeMap<>();
7
8 // Adding key-value pairs to the TreeMap
9 studentScores.put("Alice", 95);
10 studentScores.put("Bob", 80);
11 studentScores.put("Charlie", 75);
12
13 // Printing the key-value pairs in sorted order
14 for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
15 String name = entry.getKey();
16 int score = entry.getValue();
17 System.out.println(name + " - " + score);
18 }
19 }
20}
The output of the above code will be:
1Alice - 95
2Bob - 80
3Charlie - 75
The TreeSet and TreeMap classes are useful when you need to maintain ordering of elements, such as when working with sorted collections or implementing algorithms that require sorted data.