Curriculum
In Java, TreeMap
is an implementation of the NavigableMap
interface and it is used to store key-value pairs in a sorted order. It uses a red-black tree as the underlying data structure to maintain the keys in sorted order. Here’s an overview of TreeMap
in Java along with some examples.
You can create a new TreeMap
object using one of the following constructors:
// Creates an empty TreeMap with natural ordering TreeMap<K, V> map1 = new TreeMap<>(); // Creates an empty TreeMap with a custom Comparator TreeMap<K, V> map2 = new TreeMap<>(Comparator<? super K> comparator); // Creates a TreeMap with the same mappings as the given map TreeMap<K, V> map3 = new TreeMap<>(Map<? extends K, ? extends V> map);
To add elements to the TreeMap
, you can use the put()
method, which takes a key and a value:
// Creating a TreeMap with natural ordering TreeMap<Integer, String> map = new TreeMap<>(); map.put(1, "One"); map.put(3, "Three"); map.put(2, "Two");
To retrieve a value from the TreeMap
, you can use the get()
method, which takes a key and returns the associated value:
String value = map.get(2); // value is "Two"
To remove an element from the TreeMap
, you can use the remove()
method, which takes a key and removes the associated key-value pair:
map.remove(2); // removes the key-value pair with key 2
You can use a for-each loop to iterate over the entries of a TreeMap
:
for (Map.Entry<Integer, String> entry : map.entrySet()) { int key = entry.getKey(); String value = entry.getValue(); System.out.println(key + ": " + value); }
Here is an example that shows how to use TreeMap
to store student grades:
import java.util.TreeMap; public class TreeMapExample { public static void main(String[] args) { TreeMap<String, Double> grades = new TreeMap<>(); // Adding grades grades.put("Alice", 90.0); grades.put("Bob", 80.0); grades.put("Charlie", 95.0); // Updating a grade grades.put("Bob", 85.0); // Removing a grade grades.remove("Charlie"); // Printing grades for (String name : grades.keySet()) { System.out.println(name + ": " + grades.get(name)); } } }
Output:
Alice: 90.0 Bob: 85.0