HashMap Class in Java Tutorial with Example

HashMap is a Hashtable based implementation of Map interface. It is used for storing key and value pairs. It is denoted as HashMap or HashMap. This class makes no guarantee as to the order of the map.It is roughly equivalent to Hashtable except that it is unsynchronized and permits null (null values and null key).

It is not an ordered collection which means it does not return the keys and values in the same order in which they have been inserted into the HashMap. The iterator returned by HashMap is fail-fast.

HashMap Example


import java.util.*;

 public class HashMapExample {
    public static void main(String args[]) {
        
    // Declaring a HashMap of Integer keys and String values
    HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
    hashmap.put(1, "Value1");
    hashmap.put(2, "Value2");
    hashmap.put(3, "Value3");
    hashmap.put(4, "Value4");
    hashmap.put(5, "Value5");
    System.out.println("HashMap contains: "+hashmap);
     /* Get values based on key*/
    String var= hashmap.get(2);
    System.out.println("Value at key 2 is: "+var);

    /* Remove values based on key*/
    hashmap.remove(3);
    System.out.println("Map keys and values after removal:");
    Set set = hashmap.entrySet();
    Iterator it = set2.iterator();
    while(it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        System.out.print("Key is: "+pair.getKey() + " and Value is: ");
        System.out.println(pair.getValue());
    }
  }
}


Output

HashMap contains: {1=Value1, 2=Value2, 3=Value3, 4=Value4, 5=Value5}
Value at key 2 is: Value2
Map keys and values after removal:
Key is: 1 and Value is: Value1
Key is: 2 and Value is: Value2
Key is: 4 and Value is: Value4
Key is: 5 and Value is: Value5


HashMap Tutorials

Below is the list of tutorials on HashMap class.

HashMap Basics

  1. How to iterate HashMap in Java
  2. Get Size of HashMap
  3. How to check if HashMap is Empty or not
  4. Sort HashMap by Keys and Values
  5. Remove Key-Value Mapping from HashMap
  6. Remove all Key-Value Pairs from HashMap

Differences

  1. HashMap vs Hashtable
  2. HashMap vs ConcurrentHashMap
  3. HashMap vs HashSet
  4. HashMap vs ArrayList
  5. HashMap vs TreeMap
  6. HashMap vs WeakHashMap
  7. HashMap vs IdentityHashMap

Internal Working

  1. How HashMap works in Java
  2. How HashMap remove() method works Internally in Java

Serialize/Synchronize

  1. Synchronize HashMap
  2. Serialize HashMap

Get/Search

  1. Check if Key exists in HashMap
  2. Check if Value exists in HashMap
  3. Get value from HashMap using Key

Other Tutorials

  1. How to Clone a HashMap
  2. Copy One HashMap elements to Another HashMap

Reference : HashMap Oracle docs

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry