How to Remove Value from TreeMap in Java


In this example we will show how to remove a key value pair from TreeMap object with remove method.

Source Code

package com.beginner.examples;

import java.util.Collection;
import java.util.Iterator;
import java.util.TreeMap;

public class RemoveValueFromTreeMap {

	public static void main(String[] args) {
		
		//create TreeMap.
		TreeMap treeMap = new TreeMap();
		
		treeMap.put("1", "Alice");
		treeMap.put("2", "Bob");
		treeMap.put("3", "Jack");
		
		Collection collection = treeMap.values();
		Iterator iterator = collection.iterator();
		System.out.println("Before removing index of 2 , TreeMap contains :");
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}
		
		/*
		 * To remove a key value pair from TreeMap use remove method of TreeMap.
		 */
		treeMap.remove("2");
		
		Collection collection2 = treeMap.values();
		Iterator iterator2 = collection2.iterator();
		System.out.println("After removing index of 2 , TreeMap contains :");
		while(iterator2.hasNext()) {
			System.out.println(iterator2.next());
		}

	}

}

Output:

Before removing index of 2 , TreeMap contains :
Alice
Bob
Jack
After removing index of 2 , TreeMap contains :
Alice
Jack

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments