Remove TreeMap elements

We can remove elements from TreeMap using methods provided in it

Different methods which can be used to remove elements from TreeMap

Object remove(Object key)

Removes the mapping for the specified key from this map if present.

Void clear()

Removes all of the mappings from this map

pollFirstEntry()

Removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.

pollLastEntry()

Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.

Example

  1. import java.util.*;
  2. public class TreeMapRemoveExample {
  3. public static void main(String args[]) {
  4.  
  5. TreeMap<Integer,String> tm = new TreeMap<>();
  6.  
  7. tm.put(4, "Four");
  8. tm.put(5, "Five");
  9. tm.put(3, "Three");
  10. tm.put(1, "One");
  11. tm.put(2, "Two");
  12.  
  13. System.out.println("Initial TreeMap");
  14. System.out.println(tm);
  15.  
  16. tm.remove(1);
  17. System.out.println("TreeMap after removing 1 element");
  18. System.out.println(tm);
  19.  
  20. tm.pollFirstEntry();
  21. System.out.println("TreeMap after removing first entry");
  22. System.out.println(tm);
  23.  
  24. tm.pollLastEntry();
  25. System.out.println("TreeMap after removing last entry");
  26. System.out.println(tm);
  27.  
  28. tm.clear();
  29. System.out.println("TreeMap after removing all elements");
  30. System.out.println(tm);
  31.  
  32. }
  33. }
import java.util.*;
public class TreeMapRemoveExample {
public static void main(String args[]) {

TreeMap<Integer,String> tm = new TreeMap<>();

tm.put(4, "Four");
tm.put(5, "Five");
tm.put(3, "Three");
tm.put(1, "One");
tm.put(2, "Two");

System.out.println("Initial TreeMap");
System.out.println(tm);

tm.remove(1);
System.out.println("TreeMap after removing 1 element");
System.out.println(tm);

tm.pollFirstEntry();
System.out.println("TreeMap after removing first entry");
System.out.println(tm);

tm.pollLastEntry();
System.out.println("TreeMap after removing last entry");
System.out.println(tm);

tm.clear();
System.out.println("TreeMap after removing all elements");
System.out.println(tm);

}
}


We can see that, clear() method has removed all elements in TreeMap and remove() method has removed only specified element from the map.

We have used poll() method to remove first and last element from the TreeMap

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on