Remove TreeMap elements
We can remove elements from TreeMap using methods provided in it
Different methods which can be used to remove elements from TreeMap
Object remove(Object key)
Removes the mapping for the specified key from this map if present.
Void clear()
Removes all of the mappings from this map
pollFirstEntry()
Removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
pollLastEntry()
Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
Example
- import java.util.*;
- public class TreeMapRemoveExample {
- public static void main(String args[]) {
- TreeMap<Integer,String> tm = new TreeMap<>();
- tm.put(4, "Four");
- tm.put(5, "Five");
- tm.put(3, "Three");
- tm.put(1, "One");
- tm.put(2, "Two");
- System.out.println("Initial TreeMap");
- System.out.println(tm);
- tm.remove(1);
- System.out.println("TreeMap after removing 1 element");
- System.out.println(tm);
- tm.pollFirstEntry();
- System.out.println("TreeMap after removing first entry");
- System.out.println(tm);
- tm.pollLastEntry();
- System.out.println("TreeMap after removing last entry");
- System.out.println(tm);
- tm.clear();
- System.out.println("TreeMap after removing all elements");
- System.out.println(tm);
- }
- }
import java.util.*; public class TreeMapRemoveExample { public static void main(String args[]) { TreeMap<Integer,String> tm = new TreeMap<>(); tm.put(4, "Four"); tm.put(5, "Five"); tm.put(3, "Three"); tm.put(1, "One"); tm.put(2, "Two"); System.out.println("Initial TreeMap"); System.out.println(tm); tm.remove(1); System.out.println("TreeMap after removing 1 element"); System.out.println(tm); tm.pollFirstEntry(); System.out.println("TreeMap after removing first entry"); System.out.println(tm); tm.pollLastEntry(); System.out.println("TreeMap after removing last entry"); System.out.println(tm); tm.clear(); System.out.println("TreeMap after removing all elements"); System.out.println(tm); } }
We can see that, clear() method has removed all elements in TreeMap and remove() method has removed only specified element from the map.
We have used poll() method to remove first and last element from the TreeMap