HashMap

HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. This class makes no guarantees as to the order of the map. To use this class and its methods, you need to import java.util.HashMap package or its superclass.

Features

  • HashMap is a part of java.util package.

  • HashMap extends an abstract class AbstractMap which also provides an incomplete implementation of Map interface.

  • It also implements Cloneable and Serializable interface. K and V in the above definition represent Key and Value respectively.

  • HashMap doesn’t allow duplicate keys but allows duplicate values. That means A single key can’t contain more than 1 value but more than 1 key can contain a single value.

  • HashMap allows null key also but only once and multiple null values.

  • This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. It is roughly similar to HashTable but is unsynchronized.

Syntax

public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable

Constructors

HashMap()

It is the default constructor which creates an instance of HashMap with an initial capacity of 16 and load factor of 0.75.

Syntax:

HashMap<K, V> hm = new HashMap<K, V>();

HashMap(int initialCapacity)

It creates a HashMap instance with a specified initial capacity and load factor of 0.75.

Syntax:

HashMap<K, V> hm = new HashMap<K, V>(int initialCapacity);

HashMap(int initialCapacity, float loadFactor)

It creates a HashMap instance with a specified initial capacity and specified load factor.

Syntax:

HashMap<K, V> hm = new HashMap<K, V>(int initialCapacity, int  loadFactor);

HashMap(Map map)

It creates an instance of HashMap with the same mappings as the specified map.

HashMap<K, V> hm = new HashMap<K, V>(Map map);

Methods

METHODDESCRIPTION
clear()Removes all of the mappings from this map.
clone()Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
compute(K key, BiFunction<? super K, ? super V,? extends V> remappingFunction)Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
computeIfPresent(K key, BiFunction<? super K, ? super V,? extends V> remappingFunction)If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
containsKey(Object key)Returns true if this map contains a mapping for the specified key.
containsValue(Object value)Returns true if this map maps one or more keys to the specified value.
entrySet()Returns a Set view of the mappings contained in this map.
get(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
isEmpty()Returns true if this map contains no key-value mappings.
keySet()Returns a Set view of the keys contained in this map.
merge(K key, V value, BiFunction<? super V, ? super V,? extends V> remappingFunction)If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
put(K key, V value)Associates the specified value with the specified key in this map.

Operations

Adding Elements

In order to add an element to the map, we can use the put() method. However, the insertion order is not retained in the Hashmap. Internally, for every element, a separate hash is generated and the elements are indexed based on this hash to make it more efficient.

// Java program to add elements
// to the HashMap

import java.io.*;
import java.util.*;

class AddElementsToHashMap {
    public static void main(String args[])
    {
        // No need to mention the
        // Generic type twice
        HashMap<Integer, String> hm1 = new HashMap<>();

        // Initialization of a HashMap
        // using Generics
        HashMap<Integer, String> hm2
                = new HashMap<Integer, String>();

        // Add Elements using put method
        hm1.put(1, "Coding");
        hm1.put(2, "For");
        hm1.put(3, "All");

        hm2.put(1, "Coding");
        hm2.put(2, "For");
        hm2.put(3, "All");

        System.out.println("Mappings of HashMap hm1 are : "
                + hm1);
        System.out.println("Mapping of HashMap hm2 are : "
                + hm2);
    }
}

Output

Mappings of HashMap hm1 are : {1=Coding, 2=For, 3=All}
Mapping of HashMap hm2 are : {1=Coding, 2=For, 3=All}

Changing Elements

After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the map are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change.

// Java program to change
// elements of HashMap

import java.io.*;
import java.util.*;
class ChangeElementsOfHashMap {
    public static void main(String args[])
    {

        // Initialization of a HashMap
        HashMap<Integer, String> hm
                = new HashMap<Integer, String>();

        // Change Value using put method
        hm.put(1, "Coding");
        hm.put(2, "Coding");
        hm.put(3, "All");

        System.out.println("Initial Map " + hm);

        hm.put(2, "For");

        System.out.println("Updated Map " + hm);
    }
}

output

Initial Map {1=Coding, 2=Coding, 3=All}
Updated Map {1=Coding, 2=For, 3=All}

Removing Element

In order to remove an element from the Map, we can use the remove() method. This method takes the key value and removes the mapping for a key from this map if it is present in the map.

// Java program to remove
// elements from HashMap

import java.io.*;
import java.util.*;
class RemoveElementsOfHashMap{
    public static void main(String args[])
    {
        // Initialization of a HashMap
        Map<Integer, String> hm
                = new HashMap<Integer, String>();

        // Add elements using put method
        hm.put(1, "Java");
        hm.put(2, "Coding");
        hm.put(3, "For");
        hm.put(4, "All");

        // Initial HashMap
        System.out.println("Mappings of HashMap are : "
                + hm);

        // remove element with a key
        // using remove method
        hm.remove(1);

        // Final HashMap
        System.out.println("Mappings after removal are : "
                + hm);
    }
}

Output

Mappings of HashMap are : {1=Java, 2=Coding, 3=For, 4=All}
Mappings after removal are : {2=Coding, 3=For, 4=All}

Traversal of HashMap

We can use the Iterator interface to traverse over any structure of the Collection Framework. Since Iterators work with one type of data we use Entry< ? , ? > to resolve the two separate types into a compatible format. Then using the next() method we print the entries of HashMap

// Java program to traversal a
// Java.util.HashMap

import java.util.HashMap;
import java.util.Map;

public class TraversalTheHashMap {
	public static void main(String[] args)
	{
		// initialize a HashMap
		HashMap<String, Integer> map = new HashMap<>();

		// Add elements using put method
		map.put("vishal", 10);
		map.put("sachin", 30);
		map.put("vaibhav", 20);

		// Iterate the map using
		// for-each loop
		for (Map.Entry<String, Integer> e : map.entrySet())
			System.out.println("Key: " + e.getKey()
							+ " Value: " + e.getValue());
	}
}

Output

Key: vaibhav Value: 20
Key: vishal Value: 10
Key: sachin Value: 30
core java programming collections hashmap

Subscribe For More Content