How to Remove All Values from TreeMap in Java


In this example we will show how to remove all values from TreeMap object or clear TreeMap with clear method in Java.

Source Code

package com.beginner.examples;

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

public class EmptyTreeMap {

	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 all values from TreeMap , TreeMap contains :");
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}
		
		/*
		 * To remove all values or clear TreeMap use clear method of TreeMap. 
		 */
		treeMap.clear();
		
		Collection collection2 = treeMap.values();
		Iterator iterator2 = collection2.iterator();
		System.out.println("After removing all values from TreeMap , TreeMap contains :");
		while(iterator2.hasNext()) {
			System.out.println(iterator2.next());
		}

	}

}

Output:

Before removing all values from TreeMap , TreeMap contains :
Alice
Bob
Jack
After removing all values from TreeMap , TreeMap contains :

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments