TreeMap clear() in Java

clear(): This method is available in java.util.TreeMap class of Java.

Syntax:

void java.util.TreeMap.clear()

This method removes all of the mappings from this map. The map will be empty after this call returns.

Parameters: NA

Returns: NA

Exceptions: NA

Approach

Java

import java.util.TreeMap;

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

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

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        System.out.println("Before clear");
        treeMap.forEach((key, value) ->
System.out.print("Key: " + key + " Value: " + value));
        System.out.println();
        treeMap.clear();
        System.out.println("After clear");
        treeMap.forEach((key, value) ->
System.out.print("Key: " + key + " Value: " + value));
    }
}

Output:

Before clear Key: 2 Value: HelloKey: 6 Value: C++Key: 11 Value: JavaKey: 23 Value: ProgramKey: 25 Value: Program After clear


No comments:

Post a Comment