Java program to remove all elements from HashMap collection

Given a HashMap collection, we have to remove all elements from it.
Submitted by Nidhi, on June 11, 2022

Problem Solution:

In this program, we will create a collection of key/value pair information using the HashMap collection. Then we will remove all elements from HashMap using the clear() method.

Program/Source Code:

The source code to remove all elements from the HashMap collection is given below. The given program is compiled and executed successfully.

// Java program to remove all elements from 
// HashMap collection

import java.util.*;

public class Main {
  public static void main(String[] args) {
    HashMap < Integer, String > emp = new HashMap < > ();

    emp.put(101, "Amit");
    emp.put(102, "Arun");
    emp.put(103, "Akash");
    emp.put(104, "Ram");
    emp.put(105, "Mohan");

    System.out.println("HashMap 'emp' is: " + emp);

    emp.clear();

    System.out.println("HashMap 'emp' is: " + emp);
  }
}

Output:

HashMap 'emp' is: {101=Amit, 102=Arun, 103=Akash, 104=Ram, 105=Mohan}
HashMap 'emp' is: {}

Explanation:

In the above program, we imported the "java.util.*" package to use the HashMap class. Here, we created a public class Main.

The Main class contains a main() method. The main() method is the entry point for the program. And, created an object of the HashMap class and store the employee information using the put() method. Then we removed all elements from HashMap using the clear() method and printed the updated HashMap collection.

Java HashMap Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.