beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Remove all mappings from TreeMap example – Java

By Chaitanya Singh | Filed Under: Java Collections

This is how to remove all the key-value mappings from TreeMap and make it empty. We are using clear() method of TreeMap class to perform this update.

import java.util.TreeMap;
 
public class RemoveAllExample {
 
  public static void main(String[] args) {
 
    // Create a TreeMap
    TreeMap<String, String> treemap = new TreeMap<String, String>();
 
    // Add key-value pairs to the TreeMap
    treemap.put("Key1","Item1");
    treemap.put("Key2","Item2");
    treemap.put("Key3","Item3");
    treemap.put("Key4","Item4");
    treemap.put("Key5","Item5");
 
    // TreeMap elements before calling clear()
    System.out.println("Before: TreeMap contains: "+treemap);
 
    // Make TreeMap empty
    /* public void clear(): It removes all of the mappings from 
     * this map. The map will be empty after this call returns.
     */
    treemap.clear();
 
    //TreeMap elements after calling clear()
    System.out.println("After: TreeMap contains: "+treemap);
  }
}

Output:

Before: TreeMap contains: {Key1=Item1, Key2=Item2, Key3=Item3, Key4=Item4, Key5=Item5}
After: TreeMap contains: {}

Reference:
TreeMap – clear() method

Enjoyed this post? Try these related posts

  1. How to get the size of TreeMap example – Java
  2. Hashtable in java with example
  3. Java – Get element from specific index of LinkedList example
  4. How to empty an ArrayList in Java
  5. How to loop HashMap in java
  6. Difference between Iterator and ListIterator in java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap