TreeMap
Sun Jun 09 2024 10:23:11 GMT+0000 (Coordinated Universal Time)
Saved by @login
import java.util.*;
public class TreeMapExample {
public static void main(String[] args) {
// Creating a TreeMap
TreeMap<Integer, String> treeMap = new TreeMap<>();
// Adding elements to the TreeMap
treeMap.put(1, "Apple");
treeMap.put(4, "Mango");
treeMap.put(5, "Grapes");
treeMap.put(2, "Banana");
treeMap.put(3, "Orange");
// Printing the TreeMap
System.out.println("TreeMap: " + treeMap);
// Getting the size of the TreeMap
System.out.println("Size of TreeMap: " + treeMap.size());
// Checking if TreeMap is empty
System.out.println("Is TreeMap empty? " + treeMap.isEmpty());
// Getting value associated with a key
System.out.println("Value associated with key 3: " + treeMap.get(3));
// Checking if TreeMap contains a key
System.out.println("Does TreeMap contain key 4? " + treeMap.containsKey(4));
// Checking if TreeMap contains a value
System.out.println("Does TreeMap contain value 'Grapes'? " + treeMap.containsValue("Grapes"));
// Removing an element from TreeMap
treeMap.remove(2);
System.out.println("After removing key 2: " + treeMap);
// Getting the first key and value
System.out.println("First key in TreeMap: " + treeMap.firstKey());
System.out.println("First value in TreeMap: " + treeMap.firstEntry().getValue());
// Getting the last key and value
System.out.println("Last key in TreeMap: " + treeMap.lastKey());
System.out.println("Last value in TreeMap: " + treeMap.lastEntry().getValue());
// Getting a submap from TreeMap
SortedMap<Integer, String> subMap = treeMap.subMap(1, 4);
System.out.println("Submap from key 1 to key 3: " + subMap);
// Clearing the TreeMap
treeMap.clear();
System.out.println("TreeMap after clearing: " + treeMap);
}
}



Comments