import java.util.Map; import java.util.TreeMap; public class TreeMapExample { public static void main(String[] args) { // Creating a TreeMap to store names and ages TreeMap<String, Integer> ageMap = new TreeMap<>(); // Adding key-value pairs to the TreeMap ageMap.put("John", 30); ageMap.put("Alice", 25); ageMap.put("Bob", 35); ageMap.put("Eve", 28); // Accessing values using get() method System.out.println("Age of John: " + ageMap.get("John")); System.out.println("Age of Alice: " + ageMap.get("Alice")); // Updating a value using put() method ageMap.put("John", 32); System.out.println("Updated age of John: " + ageMap.get("John")); // Checking if a key exists String name = "Bob"; if (ageMap.containsKey(name)) { System.out.println(name + " exists in the map."); } else { System.out.println(name + " does not exist in the map."); } // Removing an entry using remove() method ageMap.remove("Eve"); System.out.println("Map after removing Eve: " + ageMap); // Iterating over map entries using for-each loop System.out.println("Iterating over map entries:"); for (Map.Entry<String, Integer> entry : ageMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } // Checking size and emptiness System.out.println("Size of map: " + ageMap.size()); System.out.println("Is map empty? " + ageMap.isEmpty()); // Checking if map contains a key and value System.out.println("Contains key 'Bob': " + ageMap.containsKey("Bob")); System.out.println("Contains value 35: " + ageMap.containsValue(35)); // Clear the map ageMap.clear(); System.out.println("Map after clearing: " + ageMap); } }