import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
// create a TreeMap
TreeMap<String, Integer> treeMap = new TreeMap<>();
// put some key-value pairs in the map
treeMap.put("Alice", 25);
treeMap.put("Bob", 30);
treeMap.put("Charlie", 35);
// print the TreeMap
System.out.println("TreeMap: " + treeMap);
// get the value associated with a key
int bobAge = treeMap.get("Bob");
System.out.println("Bob's age: " + bobAge);
// remove a key-value pair from the map
treeMap.remove("Charlie");
System.out.println("TreeMap after removing Charlie: " + treeMap);
// get the size of the map
int size = treeMap.size();
System.out.println("Size of the TreeMap: " + size);
// get the first and last keys in the map
String firstKey = treeMap.firstKey();
String lastKey = treeMap.lastKey();
System.out.println("First key: " + firstKey);
System.out.println("Last key: " + lastKey);
}
}
This code creates a TreeMap
called treeMap
, which maps String
keys to Integer
values. We then add some key-value pairs to the map using the put()
method.
We then print the entire TreeMap
using the println()
method.
We retrieve the value associated with the key "Bob"
using the get()
method, and print it.
We then remove the key-value pair associated with the key "Charlie"
using the remove()
method.
We use the size()
method to determine the number of key-value pairs in the map, and print it.
Finally, we use the firstKey()
and lastKey()
methods to retrieve the first and last keys in the map, respectively, and print them.
The output of this code will be:
TreeMap: {Alice=25, Bob=30, Charlie=35}
Bob's age: 30
TreeMap after removing Charlie: {Alice=25, Bob=30}
Size of the TreeMap: 2
First key: Alice
Last key: Bob
This example demonstrates some of the basic operations that can be performed using a TreeMap
.