Delete an item from TreeMap in Java

Deleting in object collections is very easy and using the same function that is implemented in the root of the collection hierarchy of the Map and Collection interface.

The example below shows how to remove a key and its value from TreeMap using the remove() which returns the value that was deleted, otherwise in case the key is non-existent, it returns null.

import java.util.*; 

public class TreeMap_remove {
public static void main(String[] args) {
// creating TreeMap
TreeMap< Integer, String> treemap = new TreeMap< Integer, String> ();

// insert into treemap
treemap.put(1, "a1");
treemap.put(2, "a2");
treemap.put(3, "a3");
treemap.put(4, "a4");

//display elements
Set set=treemap.keySet();
Iterator it = set.iterator();
while(it.hasNext()){
Integer key = ((Integer) it.next());
String val = ((String) treemap.get(key));
System.out.println(key+"-> "+val);
}

System.out.println("initial treemap size: "+treemap.size()+" element(s)");

//remove the second and fourth element
String val2 = treemap.remove(2);
String val4 = treemap.remove(4);

//show items after deletion
System.out.println("\nafter deletion");
set=treemap.keySet();
it = set.iterator();
while(it.hasNext()){
Integer key = ((Integer) it.next());
String val = ((String) treemap.get(key));
System.out.println(key+"-> "+val);
}
System.out.println("after removing the values "+val2+" " +
" and "+val4+": "+treemap.size()+" element(s)");
}
}
Output:

1-> a1
2-> a2
3-> a3
4-> a4
initial treemap size: 4 element(s)

after deletion
1-> a1
3-> a3
after removing the a2 and a4 values: 2 element(s)
References:
JavaDoc: TreeMap remove method