Java Program to remove a key from a TreeMap only if it is associated with a given value


Use the remove() method to remove a key from a TreeMap only if it is associated with a given value. 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");

To remove a key, set the key and the associated value here. If the associate value exists, then the key will get removed −

m.remove(3, "Australia")

The following is an example to remove a key from a TreeMap only if it is associated with a given value −

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);
      // removing a key associated with a given value
      System.out.println("Key removed? "+m.remove(3, "Australia"));
      System.out.println("Updated TreeMap Elements = "+m);
   }
}

Output

TreeMap Elements = {1=India, 2=US, 3=Australia, 4=Netherlands, 5=Canada}
Key removed? true
Updated TreeMap Elements = {1=India, 2=US, 4=Netherlands, 5=Canada}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements