In this tutorial we are gonna see how to remove a Key-value mapping from TreeMap. We are using remove(Object key) method of TreeMap class to perform this remove.
import java.util.TreeMap; public class Details { public static void main(String[] args) { // Create a TreeMap TreeMap<String, String> treemap = new TreeMap<String, String>(); // Add key-value pairs to the TreeMap treemap.put("Key1","Item1"); treemap.put("Key2","Item2"); treemap.put("Key3","Item3"); treemap.put("Key4","Item4"); treemap.put("Key5","Item5"); // TreeMap Elements Before remove System.out.println("Before: TreeMap contains: "+treemap); // Removing element which is mapped to Key3 /* public V remove(Object key): Removes the mapping * for this key from this TreeMap if present. */ Object removedElement = treemap.remove("Key3"); System.out.println("Removed Element: "+removedElement); // TreeMap Elements after remove System.out.println("After: TreeMap contains: "+treemap); } }
Output:
Before: TreeMap contains: {Key1=Item1, Key2=Item2, Key3=Item3, Key4=Item4, Key5=Item5} Removed Element: Item3 After: TreeMap contains: {Key1=Item1, Key2=Item2, Key4=Item4, Key5=Item5}
Reference:
TreeMap – remove(Object key) method
Leave a Reply