Java TreeMap.clear() example

In this java tutorial, You will learn how to use clear() method of TreeMap class.The clear() method is used to remove all of the mappings from this map. The map will be empty after this call returns.

Removes all of the mappings from this map.

syntax

public void clear()

Java TreeMap clear() example

  • Create TreeMap instance new TreeMap < Integer, String > ();
  • Add few elements in TreeMap e.g. students.put(1, "Pooja");
  • Print the TreeMap values.
  • students.clear(); It will remove / clear the TreeMap.
  • It will print empty TreeMap.
package com.technicalkeeda;

import java.util.TreeMap;

public class App {
    public static void main(String args[]) {

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

        students.put(1, "Pooja");
        students.put(2, "Ajit");
        students.put(3, "Yashwant");
        students.put(4, "Aditi");

        System.out.println("TreeMap values :- " + students);
        students.clear();
        System.out.println("TreeMap after clear() :- " + students);
    }
}

output

TreeMap values :- {1=Pooja, 2=Ajit, 3=Yashwant, 4=Aditi}
TreeMap after clear() :- {}