Java Map clear() Method Tutorial

In this section, we will learn what the Map clear() method is and how to use it in Java.

What is Java Map clear() Method?

The Java Map clear() method is used to clear the entire elements (entries) of a Map object.

This means after calling the method, the size of the target Map object will be set to 0.

Java clear() Method Syntax:

void clear();

clear() Method Parameters:

The method does not take an argument.

clear() Method Return Value:

The return value of the method is void.

clear() Method Exceptions:

The method might throw one exception and that is:

UnsupportedOperationException: we get this exception if the clear() method is not supported with the target Map object.

Example: using Map clear() method

import java.util.Map; 
import java.util.HashMap;
import java.util.Set;
class Main{
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        map.put("Omid","Dehghan");
        map.put("Jack","Bauer");
        map.put("Barack","Obama");
        map.put("Elon","Musk");
        map.put("Lex","Fridman");

        System.out.println("The size of the map object before calling the clear() method: "+map.size());
        map.clear();
        System.out.println("The size of the map object after calling the clear() method: "+ map.size());
    }
}

Output:

The size of the map object before calling the clear() method: 5

The size of the map object after calling the clear() method: 0
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies