HashMap in Java

HashMap

In the last blog, we learned about the NavigableMap interface. To know more about the NavigableMap interface, visit NavigableMap Interface in Java. In this blog, we will learn about the class called HashMap.


HashMap

HashMap class is a class that provides the basic implementation of the Map interface. Like in Map, we use key-value pairs to store the data. The same approach is used in HashMap too. One object is used as a key to other objects. The key in the HashMap should be unique. If we try to use a duplicate key, it will replace the corresponding key element. HashMap is similar to HashTable but the difference is that the HapMap is not synchronized. HashMap allows a null key as well but there should be only one null key and there can be multiple null values. In order to use the HashMap we have to import the package called java.util. Let's see the example:

e.g.

import java.util.HashMap;
public class HashMapEx {
  public static void main(String[] args) {
    HashMap<Integer, String> hashMap = new HashMap<>();
    hashMap.put(1004, "John");
    hashMap.put(1006, "Smith");
    hashMap.put(1002, "Joe");
    hashMap.put(1009, "Justin");
    System.out.println("HashMap: "+ hashMap);
  }
}

Output

HashMap: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}

HashMap Constructors

  1. HashMap() - HashMap() is used to construct a default HashMap.
  2. HashMap(int initialCapacity) - HashMap(int initialCapacity) is used to initialize the capacity of the hash map to the given integer value, capacity.
  3. HashMap(int capacity, float loadFactor) - HashMap(int capacity, float loadFactor) is used to initialize both the capacity and load factor of the hash map with the help of its arguments.
  4. HashMap(Map <? extends Key,? extends Value> m) - HashMap(Map <? extends Key,? extends Value> m) is used to initialize the hash map by using the elements of the given Map object m.
  5. e.g.

    Map<String, String> hashMap1 = new HashMap<>();
    Map<String, String> hashMap2 = new HashMap<>(2^4);
    Map<String, String> hashMap3 = new HashMap<>(16,0.90f);
    Map<String, String> hashMap4 = new HashMap<>(hashMap1);

Methods of HashMap

  1. clear()
  2. clear() method removes all the key-value pairs of the hashmap.

    e.g.

    import java.util.HashMap;
    public class HashMapClearEx {
    public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1004, "John");
        hashMap.put(1006, "Smith");
        hashMap.put(1002, "Joe");
        hashMap.put(1009, "Justin");
        System.out.println("HashMap: "+ hashMap);
        hashMap.clear();
        System.out.println("HashMap after using clear() method: "+ hashMap);
      }
    }

    Output

    HashMap: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
    HashMap after using clear() method: {}
  3. clone()
  4. clone() method is used to return a shallow copy of the HashMap instance. A shallow copy means references of key and value are copied not key and value.

    e.g.

    import java.util.HashMap;
    public class HashMapCloneEx {
      public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1004, "John");
        hashMap.put(1006, "Smith");
        hashMap.put(1002, "Joe");
        hashMap.put(1009, "Justin");
        System.out.println("HashMap: "+ hashMap);
        HashMap<Integer, String> cloneHashMap = (HashMap<Integer, String>)hashMap.clone();
        System.out.println("Cloned HashMap: " + cloneHashMap);
      }
    }

    Output

    HashMap: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
    Cloned HashMap: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
  5. isEmpty()
  6. isEmpty() method checks whether the hashmap is empty or not.

    e.g

    import java.util.HashMap;
    public class HashMapIsEmptyEx {
      public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        System.out.println("HashMap: "+ hashMap);
        System.out.println("Is the HashMap empty: "+ hashMap.isEmpty());
        hashMap.put(1004, "John");
        hashMap.put(1006, "Smith");
        hashMap.put(1002, "Joe");
        hashMap.put(1009, "Justin");
        System.out.println("HashMap after adding elements: " + hashMap);
        System.out.println("Is the HashMap empty: "+ hashMap.isEmpty());
      }
    }

    Output

    HashMap: {}
    Is the HashMap empty: true
    HashMap after adding elements: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
    Is the HashMap empty: false
  7. size()
  8. size() method returns the number of entries in the hashmap.

    e.g.

    import java.util.HashMap;
    public class HashMapSizeEx {
      public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1004, "John");
        hashMap.put(1006, "Smith");
        hashMap.put(1002, "Joe");
        hashMap.put(1009, "Justin");
        System.out.println("HashMap: "+ hashMap);
        System.out.println("The size of the HashMap is: "+ hashMap.size());
      }
    }

    Output

    HashMap: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
    The size of the HashMap is: 4
  9. put()
  10. put() method adds or insert the elements in the Hashmap.

    e.g.

    import java.util.HashMap;
      public class HashMapPutEx {
       public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1004, "John");
        hashMap.put(1006, "Smith");
        hashMap.put(1002, "Joe");
        hashMap.put(1009, "Justin");
        System.out.println("HashMap: "+ hashMap);
      }
    }

    e.g.

    HashMap: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
  11. putAll()
  12. putAll() method adds or inserts all the key-value mappings from the specified Map to the HashMap.

    e.g.

    import java.util.HashMap;
      public class HashMapPutAllEx {
       public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1004, "John");
        hashMap.put(1006, "Smith");
        hashMap.put(1002, "Joe");
        hashMap.put(1009, "Justin");
        System.out.println("HashMap: "+ hashMap);
        HashMap<Integer, String> hashMap2 = new HashMap<>();
        hashMap2.put(1005, "Donna");
        hashMap2.put(1001, "Charles");
        hashMap2.put(1007, "Brean");
        hashMap2.put(1003, "Chris");
        System.out.println("HashMap2: "+ hashMap2);
        hashMap.putAll(hashMap2);
        System.out.println("After using PutAll(): "+ hashMap);
      }
    }

    Output

    HashMap: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
    HashMap2: {1001=Charles, 1003=Chris, 1005=Donna, 1007=Brean}
    After using PutAll(): {1009=Justin, 1001=Charles, 1002=Joe, 1003=Chris, 1004=John, 1005=Donna, 1006=Smith, 1007=Brean}
  13. putIfAbsent()
  14. putIfAbsent() method inserts the specified value with the specified key in the map only if it is not already present in the hashmap.

    e.g.

    import java.util.HashMap;
    public class HashMapPutIfAbsentEx {
      public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1004, "John");
        hashMap.put(1006, "Smith");
        hashMap.put(1002, "Joe");
        hashMap.put(1009, "Justin");
        System.out.println("HashMap: "+ hashMap);
        hashMap.putIfAbsent(1008, "Gil");
        System.out.println("After using putIfAbsent() on the HashMap: "+ hashMap);
        HashMap<Integer, String> hashMap2 = new HashMap<>();
        hashMap2.put(1005, "Donna");
        hashMap2.put(1001, "Charles");
        hashMap2.put(1007, "Brean");
        hashMap2.put(1003, "Chris");
        System.out.println("HashMap2: "+ hashMap2);
        hashMap2.putIfAbsent(1003, "Chris");
        System.out.println("After using putIfAbsent() on the HashMap when the element is already present: "+ hashMap2);
      }
    }

    Output

    HashMap: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
    After using putIfAbsent() on the HashMap: {1008=Gil, 1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
    HashMap2: {1001=Charles, 1003=Chris, 1005=Donna, 1007=Brean}
    After using putIfAbsent() on the HashMap when the element is already present: {1001=Charles, 1003=Chris, 1005=Donna, 1007=Brean}
  15. remove()
  16. remove() method removes or deletes the specified values with the associated specified keys from the map.

    e.g.

    import java.util.HashMap;
    public class HashMapRemoveEx {
      public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1004, "John");
        hashMap.put(1006, "Smith");
        hashMap.put(1002, "Joe");
        hashMap.put(1009, "Justin");
        System.out.println("HashMap: "+ hashMap);
        hashMap.remove(1006);
        System.out.println("After using remove() on the HashMap: "+ hashMap);
      }
    }

    Output

    HashMap: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
    After using remove() on the HashMap: {1009=Justin, 1002=Joe, 1004=John}
  17. containsKey()
  18. The containsKey() method determines whether the mapping for the supplied key exists in the hashmap. If the key is missing, it returns false.

    e.g.

    import java.util.HashMap;
    public class HashMapContainsKeyEx {
      public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1004, "John");
        hashMap.put(1006, "Smith");
        hashMap.put(1002, "Joe");
        hashMap.put(1009, "Justin");
        System.out.println("HashMap: "+ hashMap);
        System.out.println("Is the key present: "+ hashMap.containsKey(1002));
        System.out.println("Is the key present: "+ hashMap.containsKey(1008));
      }
    }

    Output

    HashMap: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
    Is the key present: true
    Is the key present: false
  19. containsValue()
  20. containsValue() method checks if the specified value is present in one or more mappings of the hashmap or not. If the value is not present then it returns false.

    e.g.

    import java.util.HashMap;
    public class HashMapContainsValueEx {
      public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1004, "John");
        hashMap.put(1006, "Smith");
        hashMap.put(1002, "Joe");
        hashMap.put(1009, "Justin");
        System.out.println("HashMap: "+ hashMap);
        System.out.println("Is the value present: "+ hashMap.containsKey("Smith"));
        System.out.println("Is the value present: "+ hashMap.containsKey("Steve"));
      }
    }

    Output

    HashMap: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
    Is the value present: false
    Is the value present: false
  21. replace()
  22. replace() method replaces the old value with the new value for a specified key.

    e.g.

    import java.util.HashMap;
    public class HashMapReplaceEx {
      public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1004, "John");
        hashMap.put(1006, "Smith");
        hashMap.put(1002, "Joe");
        hashMap.put(1009, "Justin");
        System.out.println("HashMap: "+ hashMap);
        System.out.println("Replaced value: "+ hashMap.replace(1002, "Steve"));
        System.out.println("Updated HashMap: "+ hashMap);
      }
    }

    Output

    HashMap: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
    Replaced value: Joe
    Updated HashMap: {1009=Justin, 1002=Steve, 1004=John, 1006=Smith}
  23. get()
  24. get() method returns the value of the specified key in the hashmap.

    e.g.

    import java.util.HashMap;
    public class HashMapGetEx {
      public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1004, "John");
        hashMap.put(1006, "Smith");
        hashMap.put(1002, "Joe");
        hashMap.put(1009, "Justin");
        System.out.println("HashMap: "+ hashMap);
        System.out.println("Value of the specified key: "+ hashMap.get(1002));
      }
    }

    Output

    HashMap: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
    Value of the specified key: Joe
  25. keySet()
  26. The keySet() method is used to return a set view of the keys present in this map.

    e.g.

    import java.util.HashMap;
    public class HashMapKeySetEx {
      public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1004, "John");
        hashMap.put(1006, "Smith");
        hashMap.put(1002, "Joe");
        hashMap.put(1009, "Justin");
        System.out.println("HashMap: "+ hashMap);
        System.out.println("Key Sets: "+ hashMap.keySet());
      }
    }

    Output

    HashMap: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
    Key Sets: [1009, 1002, 1004, 1006]
  27. values()
  28. values() method returns the view of all the values present in the entries of the hashmap.

    e.g.

    import java.util.HashMap;
    public class HashMapValuesEx {
      public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1004, "John");
        hashMap.put(1006, "Smith");
        hashMap.put(1002, "Joe");
        hashMap.put(1009, "Justin");
        System.out.println("HashMap: "+ hashMap);
        System.out.println("Values: "+ hashMap.values());
      }
    }

    Output

    HashMap: {1009=Justin, 1002=Joe, 1004=John, 1006=Smith}
    Values: [Justin, Joe, John, Smith]
Get in Touch

Atrowel will be pleased to receive your feedback and suggestions. Those of you who would like to contribute, please send us an email.