Remove a key from TreeMap in Java

Java 8Object Oriented ProgrammingProgramming

Use the remove() method to remove a key from TreeMap.

Let us first create a TreeMap and add some elements −

TreeMap<Integer,String> m = new TreeMap<Integer,String>();
m.put(1,"India");
m.put(2,"US");
m.put(3,"Australia");
m.put(4,"Netherlands");
m.put(5,"Canada");

Let us remove a key now. Here, we are removing key 3 now −

m.remove(3)

The following is an example to remove a key from TreeMap −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      TreeMap<Integer,String> m = new TreeMap<Integer,String>();
      m.put(1,"India");
      m.put(2,"US");
      m.put(3,"Australia");
      m.put(4,"Netherlands");
      m.put(5,"Canada");
      System.out.println("TreeMap Elements = "+m);
      System.out.println("Removing a Key = "+m.remove(3));
      System.out.println("Updated TreeMap Elements = "+m);
   }
}

Output

TreeMap Elements = {1=India, 2=US, 3=Australia, 4=Netherlands, 5=Canada}
Removing a Key = Australia
Updated TreeMap Elements = {1=India, 2=US, 4=Netherlands, 5=Canada}
raja
Published on 30-Jan-2019 12:43:23
Advertisements