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
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – Remove all mappings from HashMap example

By Chaitanya Singh | Filed Under: Java Collections

Example

In the last tutorial we shared how to remove a specific mapping from HashMap based on key. In this example we are going to see how to remove all the mappings from HashMap. We will be using clear() method of HashMap class to do this:

public void clear(): Removes all of the mappings from this map. The map will be empty after this call returns.

Complete Code:

import java.util.HashMap;

public class RemoveAllExample {
 
 public static void main(String[] args) {
 
    // Creating a HashMap of int keys and String values
    HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
 
    // Adding Key and Value pairs to HashMap
    hashmap.put(11,"Value1");
    hashmap.put(22,"Value2");
    hashmap.put(33,"Value3");
    hashmap.put(44,"Value4");
    hashmap.put(55,"Value5");
 
    // Displaying HashMap Elements
    System.out.println("HashMap Elements: " + hashmap);

    // Removing all Mapping
    hashmap.clear();

    // Displaying HashMap Elements after remove
    System.out.println("After calling clear():");
    System.out.println("---------------------");
    System.out.println("HashMap Elements: " + hashmap); 
 }
}

Output:

HashMap Elements: {33=Value3, 55=Value5, 22=Value2, 11=Value1, 44=Value4}
After calling clear():
---------------------
HashMap Elements: {}

As you can see all the mappings of HashMap have been removed after calling clear() method and HashMap became empty after that.

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 – 2022 BeginnersBook . Privacy Policy . Sitemap