TreeSet and TreeMap are two implementations of the SortedSet and SortedMap interfaces in the Java Collections Framework, respectively. While they both use a tree data structure to store elements and maintain ordering, there are some key differences between the two:
Element ordering: TreeSet orders its elements based on their natural ordering (as determined by the Comparable interface), or based on a Comparator provided at construction time. TreeMap orders its key-value pairs based on the keys’ natural ordering (again, as determined by the Comparable interface), or based on a Comparator provided at construction time.
Internal data structure: TreeSet uses a NavigableMap (specifically, a TreeMap) to store its elements, while TreeMap uses a NavigableSet (specifically, a TreeSet) to store its keys.
Allowed values: TreeSet only stores unique elements (as determined by their compareTo() method or the Comparator), while TreeMap can store duplicate keys, but not duplicate values.
Performance: TreeSet generally has better performance than TreeMap for operations that involve inserting, deleting, or searching for elements, because TreeSet only needs to perform these operations on a single value, while TreeMap needs to perform them on key-value pairs.
Here’s an example of how to use TreeSet and TreeMap in Java:
import java.util.TreeSet;
import java.util.TreeMap;
public class Example {
public static void main(String[] args) {
// create a TreeSet of strings
TreeSet<String> myTreeSet = new TreeSet<>();
myTreeSet.add("c");
myTreeSet.add("a");
myTreeSet.add("b");
// create a TreeMap of strings
TreeMap<String, Integer> myTreeMap = new TreeMap<>();
myTreeMap.put("c", 3);
myTreeMap.put("a", 1);
myTreeMap.put("b", 2);
// iterate over the elements of the TreeSet
for (String element : myTreeSet) {
System.out.println(element);
}
// iterate over the entries of the TreeMap
for (var entry : myTreeMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
In this example, we create a TreeSet of strings called "myTreeSet" and add three elements to it. We also create a TreeMap of strings to integers called "myTreeMap" and add three key-value pairs to it. We then iterate over the elements of the TreeSet using a for-each loop, and over the entries of the TreeMap using the entrySet() method and a for-each loop with the var keyword.
The output of this program would be:
a
b
c
a: 1
b: 2
c: 3
As you can see, TreeSet orders its elements alphabetically, while TreeMap orders its entries alphabetically by key.
In summary, TreeSet and TreeMap are both implementations of the SortedSet and SortedMap interfaces in the Java Collections Framework that use a tree data structure to store elements and maintain ordering. They differ in the ordering of elements or key-value pairs, the internal data structure used, the allowed values, and the performance characteristics of various operations.