- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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}
- Related Articles
- Java Program to remove a key from a HashMap only if it is associated with a given value
- Remove a key from TreeMap in Java
- Remove a value from TreeMap in Java
- Get the value associated with a given key in Java HashMap
- Modify the value associated with a given key in Java HashMap
- Java Program to check if a particular key exists in TreeMap
- Java Program to remove a key from a HashMap
- Java Program to check if a particular value exists in TreeMap
- Java Program to remove key value pair from HashMap?
- Create a TreeMap in Java and add key-value pairs
- Java Program to get highest key stored in TreeMap
- Select a value from MySQL database only if it exists only once from a column with duplicate and non-duplicate values
- Java program to remove all duplicates words from a given sentence
- Remove all values from TreeMap in Java
- Remove a value from Java LinkedHashMap

Advertisements