HashMap in Java

Since Java 1.2, HashMap<Key, Value> has been part of the Java collection. The java.util package contains this class. It implements the Java Map interface in its most basic form. It holds data as (Key, Value) pairs that can be accessed using a different index type (e.g., an Integer). A key (index) refers to another object (value). Trying to insert the duplicate key overwrites the associated key’s element.

HashMap is comparable to HashTable but without synchronization. It also allows for the storage of null keys. However, there should only be one null key object and an unlimited number of null values. This class does not guarantee the order of the Map. Import the java.util. HashMap package or its superclass to utilize this class and its methods.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>// program for illustrating the HashMap class of java.util package in Java

// First, import the HashMap class
import java.util.HashMap;

// Main class
public class Codeunderscored {

	// Declaration of the Main method
	public static void main(String[] args)
	{
		// Creation of a hash map that is empty by declaring the object
		// of string and integer type
		HashMap<String, Integer> hashMap = new HashMap<>();

		//elements' addition to the Map using the standard method put()

		hashMap.put("kane", 10);
		hashMap.put("rock", 30);
		hashMap.put("undertaker", 20);

		// Printing the size & content of the Hash Map
		System.out.println("Size of Hash Map is:- "+ hashMap.size());

		// Printing the items in object of Map
		System.out.println(hashMap);

		// Checking for the presence of a key and, if so, printing the value using a random element
		if (hashMap.containsKey("kane")) {

			// Mapping
			Integer aVar = hashMap.get("kane");

			// Printing the value's corresponding key
			System.out.println("value for key"+ " \"kane\" is:- " + aVar);
		}
	}
}
</pre>
</div>

The syntax is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>public class HashMap<K,V> extends AbstractMap<K,V>
                          implements Map<K,V>, Cloneable, Serializable</pre>
</div>

It accepts two parameters, which are as follows:

  • The type of keys that this map keeps track of
  • The mapped values’ type

HashMap implements serializable, Cloneable, and Map<K, V> interfaces. AbstractMap<K, V> is extended by HashMap. LinkedHashMap and PrinterStateReasons are direct subclasses.

  • HashMap constructors are as follows:
  • HashMap has four constructors, each of which has a public access modifier and is listed below:
  • HashMap()
  • HashMap (int initialCapacity)
  • HashMap (int initialCapacity, float loadFactor)
  • HashMap (Map map)

We’ll go over each of the constructors and how to build them using clean Java programs.

The first Constructor: HashMap()

It’s the default constructor, and it generates a HashMap instance with a capacity of 16 and a load factor of 0.75.

The syntax is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>HashMap<K, V> hashMap = new HashMap<K, V>();</pre>
</div>

Example: Program for demonstrating how to use the HashMap() constructor in Java

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>// Importing the necessary classes required
import java.io.*;
import java.util.*;

// The Primary class for adding elements to the HashMap

class Codeunderscored {

	// Main static method in java
	public static void main(String args[])
	{
		// There is absolutely no reason for mentioning the Generic type twice
		HashMap<Integer, String> hashMapOne = new HashMap<>();

		// Initializing the HashMap using Generics
		HashMap<Integer, String>  hashMapTwo = new HashMap<Integer, String>();

		// Adding elements using put method
		// Custom input elements
		hashMapOne.put(3, "three");
		hashMapOne.put(4, "four");
		hashMapOne.put(5, "five");

		hashMapTwo.put(7, "seven");
		hashMapTwo.put(8, "eight");
		hashMapTwo.put(9, "Nine");

		// Print and show the  mapping of HashMap 1
		System.out.println("The Mappings of the HashMap hashMapOne are : "+ hashMapOne);

		// Print and show the mapping of HashMap 2
		System.out.println("The Mapping of the HashMap hashMapTwo are : "+ hashMapTwo);
	}
}</pre>
</div>

The output is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>The Mappings of HashMap hashMapOne are : {3=three, 4=four, 5=five}
The Mapping of HashMap hashMapTwo are : {7=seven, 8=eight, 9=nine}</pre>
</div>

Second Constructor: HashMap(int initialCapacity)

It generates a HashMap object with a 0.75 load factor and a specified initial capacity. The syntax is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>HashMap<K, V> hashMap = new HashMap<K, V>(int initialCapacity);</pre>
</div>

Example: Program for demonstrating HashMap(int initialCapacity) Constructor in Java

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>// Importing the necessary needed classes
import java.io.*;
import java.util.*;

// The primary class to add HashMap items
class pushElementsToHashMap {

	// Main driver method
	public static void main(String args[])
	{
		//It's needless repeating the Generic type.
		HashMap<Integer, String> hashMapOne = new HashMap<>(10);

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

		// Adding elements to object of HashMap
		// using put method

		// HashMap One
		hashMapOne.put(4, "four");
		hashMapOne.put(5, "five");
		hashMapOne.put(6, "six");

		// HashMap Two
		hashMapTwo.put(7, "seven");
		hashMapTwo.put(8, "eight");
		hashMapTwo.put(9, "nine");

		// Print HashMap One elements
		System.out.println("The Mappings of the HashMap hashMapOne are : "
						+ hashMapOne);

		// Print HashMap Two elements
		System.out.println("The Mapping of the HashMap hashMapTwo are : "
						+ hashMapTwo);
	}
}
</pre>
</div>

The resultant output is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>The Mappings of the HashMap hashMapOne are: {4=four, 5=five, 6=six}
The Mapping of the HashMap hashMapTwo are: {7=seven, 8=eight, 9=nine}</pre>
</div>

The third Constructor: HashMap(int initialCapacity, float loadFactor)

It generates a HashMap instance with the initial capacity and load factor supplied. The syntax is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>HashMap<K, V> hashMap= new HashMap<K, V>(int initialCapacity, int  loadFactor);</pre>
</div>

Example: Program for demonstrating HashMap(int initialCapacity,float loadFactor) Constructor in Java

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>// Importing the standard needed classes
import java.io.*;
import java.util.*;

// The primary class for adding elements to the HashMap
class Codeunderscored {

	// Declaration of the Main driver method
	public static void main(String args[])
	{
		// It is needless to mention the generic type a second time
		HashMap<Integer, String> hashMapOne
			= new HashMap<>(5, 0.75f);

		// Initialization of a HashMap using Generics
		HashMap<Integer, String> hashMapTwo
			= new HashMap<Integer, String>(3, 0.5f);

		//  using the put() method to add customized input elements
		
		// HashMap One
		hashMapOne.put(4, "four");
		hashMapOne.put(5, "five");
		hashMapOne.put(6, "six");

		// HashMap Two
		hashMapTwo.put(7, "seven");
		hashMapTwo.put(8, "eight");
		hashMapTwo.put(9, "nine");

		// Printing and showing elements in the hashMap one object
		System.out.println("The Mappings of the HashMap hashMapOne are : "
						+ hashMapOne);

		// Printing and showing elements in the hashMap two object
		System.out.println("The Mapping of HashMap the hashMapTwo are : "
						+ hashMapTwo);
	}
}
</pre>
</div>

The resultant output is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>The Mappings of the HashMap hashMapOne are: {4=four, 5=five, 6=six}
The Mapping of the HashMap hashMapTwo are: {7=seven, 8=eight, 9=nine}</pre>
</div>

HashMap(Map map)

This method produces a HashMap object with the same mappings as the given map. The syntax is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>HashMap<K, V> hashMap = new HashMap<K, V>(Map map);</pre>
</div>

Example: Program for demonstrating the HashMap(Map map) Constructor in Java

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.io.*;
import java.util.*;

class pushElementsToHashMap {
	public static void main(String args[])
	{
		// It is needless mentioning the Generic type twice
		Map<Integer, String> hashMapOne = new HashMap<>();

		// Add Elements using put method
		hashMapOne.put(1, "one");
		hashMapOne.put(5, "five");
		hashMapOne.put(10, "ten");

		// Initializing the HashMap using Generics
		HashMap<Integer, String>  hashMapTwo
			= new HashMap<Integer, String>(hashMapOne);

		System.out.println("The Mappings of the HashMap hashMapOne are : "
						+ hashMapOne);
		
		System.out.println("The Mapping of the HashMap hashMapTwo are : "
						+ hashMapTwo);
	}
}</pre>
</div>

Output

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>The Mappings of the HashMap hashMapOne are : {1=one, 5=five, 10=ten}
The Mapping of the HashMap hashMapTwo are : {1=one, 5=five, 10=ten}</pre>
</div>

Using HashMap to Perform Various Operations

Adding Elements

The put() method can add an element to the map. The Hashmap, on the other hand, does not keep track of the insertion order.

Internally, a different hash is generated for each element, and the elements are indexed based on this hash to improve efficiency.

Example: Program for adding elements to a given HashMap in Java

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.io.*;
import java.util.*;

class pushElementsToHashMap {
	public static void main(String args[])
	{
		// It is needless mentioning the Generic type twice
		HashMap<Integer, String> hashMapOne = new HashMap<>();

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

		// Add Elements using put method
		hashMapOne.put(1, "Code");
		hashMapOne.put(2, "Underscored");
		hashMapOne.put(3, "Dotcom");

		hashMapTwo.put(1, "Code");
		hashMapTwo.put(2, "Underscored");
		hashMapTwo.put(3, "Dotcom");

		System.out.println(" The Mappings of the HashMap hashMapOne are : "
						+ hashMapOne);
		System.out.println("The Mapping of HashMap the hashMapTwo are : "
						+ hashMapTwo);
	}
}
</pre>
</div>

The resultant output is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>The Mappings of the HashMap hm1 are: {1=Code, 2=Underscored, 3=Dotcom}
The Mapping of HashMap the hm2 are: {1=Code, 2=Underscored, 3=Dotcom}
</pre>
</div>

Changing Elements

Just in case we wish to change an element after it has been added, we can do it by using the put() method to add it again. Because the keys are used to index the items in the map, the value of the key can be altered by simply adding the updated value for the key we want to change.

Example: Program for changing the elements of the HashMap in Java

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.io.*;
import java.util.*;
class ChangeElementsOfHashMap {
	public static void main(String args[])
	{

		// Initializing the HashMap
		HashMap<Integer, String>  hashMapOne
			= new HashMap<Integer, String>();

		// Changing the specified value using the put method
		hashMapOne.put(1, "Code");
		hashMapOne.put(2, "Underscored");
		hashMapOne.put(3, "Dotcom");

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

		hashMapOne.put(2, "Coding");

		System.out.println("Updated Map " + hashMapOne);
	}
}</pre>
</div>

Removing an Element

The remove() function can delete an element from the Map. If a key is present in the map, this function takes the key value and removes the mapping for that key.

Example: Program for removing the elements from the HashMap in Java

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.io.*;
import java.util.*;

class RemovingHashMapElements{

	public static void main(String args[])
	{
		// Initializing the HashMap
		Map<Integer, String> hashMapOne
			= new HashMap<Integer, String>();

		// Add elements using put method
		hashMapOne.put(1, "Code");
		hashMapOne.put(2, "Underscored");
		hashMapOne.put(3, "Dotcom");
		hashMapOne.put(4, "Coding");

		// Initializing the HashMap
		System.out.println("The Mappings of the HashMap are : "
						+ hashMapOne);

		// removing the element with a key using the given remove method
		hashMapOne.remove(4);

		// Finalizing the HashMap
		System.out.println("The respective Mappings after removal are : "
						+ hashMapOne);
	}
}</pre>
</div>
<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>The Mappings of the HashMap are: {1=Code, 2=Underscored, 3=Dotcom, 4=Coding}
The Mappings after removal are: {1=Code, 2=Underscored, 3=Dotcom}</pre>
</div>

HashMap traversal

The Iterator interface can be used to explore any Collection Framework structure. Do we utilize Entry<? , ? > to resolve the two different types into a suitable format because Iterators only work with one data type. The items of HashMap are then printed using the next() method.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>// Example: Program for traversing a Java.util.HashMap

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

public class HashMapTraversal {

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

		// Add elements using put method
		hashMapOne.put("ken", 31);
		hashMapOne.put("white", 50);
		hashMapOne.put("brown", 90);

		// Iterate through the  hash map using a for-each loop
		for (Map.Entry<String, Integer> entry : hashMapOne.entrySet())
			System.out.println("The key is: " + entry.getKey()
							+ " The value is: " + entry.getValue());
	}
}</pre>
</div>

HashMap’s Important Features

A key is required to access a value. HashMap is named after the Hashing technique that it employs. Hashing is a method for turning a long String into a short string representing the same String. A shorter value aids indexing and search speed. Internally, HashSet uses HashMap.

HashMap has a few notable features:

  • The java.util package includes HashMap.
  • HashMap is an abstract class that extends AbstractMap and provides a partial implementation of the Map interface.
  • Cloneable and Serializable interfaces are also implemented.
  • K and V stand for Key and Value in the preceding formulation.
  • Duplicate keys are not permitted in HashMap, although duplicate values are permitted.
  • A single key cannot hold more than one value, while several keys can hold a single value.
  • HashMap also supports null keys, but only once with numerous null values.
  • This class provides no claims about the map’s arrangement, including that it will remain stable over time.
  • It’s comparable to HashTable but without synchronization.

HashMap’s Internal Structure

HashMap internally includes an array of Nodes, each of which is represented by a class with four fields:

  • int hash
  • K key
  • V value
  • Next node

The node contains a reference to its object, as can be seen. As a result, it’s a linked list.

HashMap’s performance

HashMap’s performance is determined by two parameters, which are as follows:

  • Initial Capacity
  • Load Factor

Initial Capacity

This was HashMap’s capacity when it was created (The number of buckets a HashMap can hold when the HashMap is instantiated). It starts as 2^4=16 in Java, which means it can hold 16 key-value pairs.

Load Factor

This is the percentage of capacity that will be raised after Hashmap capacity increases (The percentage fill of buckets after rehashing takes place). The default value in Java is 0.75f, which means that rehashing occurs once 75 percent of the capacity has been filled.

Threshold

The product of the Load Factor and the Initial Capacity is the Threshold. It is (16 * 0.75 = 12) in Java by default. After entering 12 key-value pairs into the HashMap, rehashing occurs.

Rehashing

Rehashing doubles HashMap’s capacity when it has reached its Threshold. HashMap in Java continues to rehash in the following order (by default): 2^4, 2^5, 2^6, 2^7, etc.

Rehashing will never be done if the starting capacity is kept high. However, increasing it raises the temporal complexity of iteration. To improve performance, it should be carefully picked. To determine the starting capacity, consider the expected number of values. The most popular load factor number is 0.75, which offers a fair time and space costs balance. The value of the load factor varies between 0 and 1.

For your information, starting with Java 8, instead of utilizing a linked list for chaining, Java now uses Self Balancing BST. The benefit of self-balancing BST is that we obtain the worst-case search time (where every key maps to the same slot) O(Log n).

HashMap with synchronization

HashMap is unsynchronized, which means that many threads can access it simultaneously. External synchronization is required if multiple threads visit this class simultaneously and at least one of them manipulates its structure. It is accomplished by synchronizing a map-encapsulating object. It can be wrapped around Collections if no such object exists. To make HashMap synchronized and avoid unintended access, use synchronizedMap(). Consider the following scenario:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>Map m = Collections.synchronizedMap(new HashMap(...));</pre>
</div>

The Map m has now been synced. If any structural alteration is made after the creation of the iterator, except through the iterator’s remove method, iterators of this class are fail-fast. It will throw ConcurrentModificationException if the iterator fails.

HashMap’s time complexity

If the hash function is appropriately built and the contents are distributed evenly throughout the buckets, HashMap provides constant time complexity for simple operations like getting and putting.

Iteration over HashMap is limited by HashMap’s capacity and the amount of key-value pairs. In essence, it is proportionate to the capacity + size. In HashMap, capacity refers to the number of buckets. As a result, keeping many buckets in HashMap at first is not a good idea.

HashMap’s Applications

HashMap is primarily a hashing implementation. It comes in handy when we need to quickly implement search, insert, and delete operations.

HashMap’s methods

K – refers to the kind of keys on the map.

V – refers to the kind of values mapped in the given map.

Clear()

This map’s mappings are completely removed using this method.

Clone()

This HashMap instance is returned as a shallow copy; the keys and values are not duplicated.

compute(K keyVal, codeFunction<? super K, ? super V,? extends V> rMappingFunction)

Calculates a mapping between the provided key and its current mapped value (or null if there is no current mapping).

computeIfPresent(K keyVal, codeFunction<? super K, ? super V,? extends V> rMappingFunction)

If the specified key’s values are present and non-null, attempts to generate a new mapping given the key and its existing mapped value.

containsKey(Object key)

If this map has a mapping for the supplied key, it returns true.

containsValue(Object value)

If this map by any chance maps to one or more keys to the supplied value, it returns true.

entrySet()

This method is responsible for returning a Set view of the mappings in this map.

get(Object key)

Returns the value to which the supplied key is mapped, or null if no mapping for the key exists in this map.

computeIfAbsent(K keyVal, Function<? super K,? extends V> mappingFunction)

Attempts to compute the value of the supplied key using the given mapping function and enters it into this map if it is not already connected with a value (or is mapped to null).

IsEmpty()

If this map has no key-value mappings, it returns true.

keySet()

This method is responsible for returning a Set view of the keys in this map.

merge(K keyVal, V valueVal, BiFunction<? super V, ? super V,? extends V> remappingFunction)

Associates the provided key with the given non-null value if it is not already associated with a value or is null.

put(K key, V value)

This map associates the supplied value with the specified key.

putAll(Map<? extends K,? extends V> m)

All mappings from the specified map are copied to this map.

remove(Object key)

If a mapping for the supplied key exists in this map, it is removed.

Size()

It is responsible for returning the number of key-value mappings in this map.

Values()

This method returns a Collection view of the values in this map.

Methods that have been inherited from the java.util.AbstractMap class

equals()

Checks for equality between the provided object and this map.

hashCode()

The method is responsible for returning the hash code value for this map.

toString()

The toString() method is responsible for returning this map’s string representation.

Methods that have been inherited from the java.util.Map interface

equals()

Checks for equality between the provided object and this map.

forEach(BiConsumer<? super K,? super V> action)

Performs the supplied action for each entry in this map until the action throws an exception. Or all entries have been processed.

getOrDefault(Object key, V defaultValue)

Returns the value to which the supplied key is mapped, or defaultValue if no mapping for the key exists in this map.

hashCode()

It returns the hash code value for this map.

putIfAbsent(K key, V value)

If the specified key does not already have a value (or is mapped to null), it is associated with the given value and returns null; otherwise, it returns the current value.

remove(Object key, Object value)

The entry is removed if the supplied key is currently mapped to the specified value.

replace(K key, V value)

It is replaced only if the provided key is currently mapped to a value.

replace(K key, V oldValue, V newValue)

If the provided key is currently mapped to the supplied value, it is replaced.

replaceAll(codeFunction<? super K,? super V,? extends V> function)

Replace the value of each entry with the result of running the supplied function on that entry until all entries have been processed. Or the function throws an error.

Example: HashMap in Java

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>    import java.util.*;  
    public class CodeHashMap{  

     public static void main(String args[]){  
       HashMap<Integer,String> hashMap=new HashMap<Integer,String>();//Creating HashMap    
       hashMap.put(1,"Apple");  //Add items in hashMap  
       hashMap.put(2,"Amazon");    
       hashMap.put(3,"Google");   
       hashMap.put(4,"Yahoo");   
       hashMap.put(5,"Twitter");   
      hashMap.put(6,"Uber");   
      hashMap.put(7,"DELL");   
           
       System.out.println("Iterating through the Hashmap");  
       for(Map.Entry m : hashMap.entrySet()){    
        System.out.println(m.getKey()+" "+m.getValue());    
       }  
    }  
    }  </pre>
</div>

We’re storing Integer as the key and String as the value in this example. Thus, the type is HashMap<Integer, String>. The elements are placed on the map using the put() method. The getKey() and getValue() methods should be used to retrieve the key and value items, respectively. The getKey() and getValue() functions are part of the Map.Entry interface.

To get an instance of Map.Entry, we must use the Map interface’s entrySet() method.

Example: HashMap has no duplicate keys

HashMap does not allow duplicate keys to be stored. If you try to store a duplicate key with a different value, the value will be replaced.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>    import java.util.*;  
    public class HashMapExample2{  
     public static void main(String args[]){  
       HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap    
       hashMap.put(1,"Apple");  //Add items in hashMap  
       hashMap.put(2,"Amazon");    
       hashMap.put(3,"Google");   
       hashMap.put(4,"Yahoo");   
       hashMap.put(5,"Twitter");   
      hashMap.put(6,"Uber");   
      hashMap.put(7,"DELL");   
       hashMap.put(1,"IBM"); //trying to create a duplicate key  
           
       System.out.println("Iterating through the Hashmap");  
       for(Map.Entry m : hashMap.entrySet()){    
        System.out.println(m.getKey()+" "+m.getValue());    
       }  
    }  
    }  
</pre>
</div>

Example: Adding components to a Java HashMap

Different approaches to adding items to a HashMap in Java are shown here.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>   import java.util.*;  

    class CodeHashMap{  
     public static void main(String args[]){  

       HashMap<Integer,String> hashMap=new HashMap<Integer,String>();    
        System.out.println("The initial item's list  : "+hashMap);  
          hashMap.put(230,"Ken");    
          hashMap.put(240,"Mike");    
          hashMap.put(250,"White");   
           
          System.out.println("Results after invoking the put() method ");  
          for(Map.Entry m:hashMap .entrySet()){    
           System.out.println(m.getKey()+" "+m.getValue());    
          }  
            
          hashMap.putIfAbsent(260, "Joy");  
          System.out.println("Results proceeding invoking putIfAbsent() method ");  
          for(Map.Entry m:hashMap .entrySet()){    
               System.out.println(m.getKey()+" "+m.getValue());    
              }  
          HashMap<Integer,String> hashMapTwo=new HashMap<Integer,String>();  
          hashMapTwo.put(270,"Brown");  
          hashMapTwo.putAll(hashMap);  
          System.out.println(" Results following invoking putAll() method ");  
          for(Map.Entry m:hashMapTwo .entrySet()){    
               System.out.println(m.getKey()+" "+m.getValue());    
              }  
     }  
    }  </pre>
</div>

Example: Removing entries from a Java HashMap

Different methods for removing items are shown here.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>   import java.util.*;  

    public class CodeHashMap {  

       public static void main(String args[]) {  

        HashMap<Integer,String> hashMap=new HashMap<Integer,String>();          
           hashMap.put(230,"Ken");    
          hashMap.put(240,"Mike");    
          hashMap.put(250,"White");   
          hashMap.put(260, "Brown");  

        System.out.println(" The original list of elements is as follows: "+hashMap);  

        //key-based removal  
        hashMap.remove(230);  
        System.out.println(" The resultant updated list of elements: "+hashMap);  

        //value-based removal  
        hashMap.remove(240);  
        System.out.println("The new updated list of elements: "+hashMap);  

        //key-value pair based removal  
        hashMap.remove(260, "Brown");  
        System.out.println("The resulting updated list of elements: "+hashMap);  
       }      
    }  </pre>
</div>

Example: Replace() items in a Java HashMap

Different approaches to replacing items are as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>    import java.util.*;  

    class CodeHashMap{  

     public static void main(String args[]){  

       HashMap<Integer,String> hashMap=new HashMap<Integer,String>();    
           hashMap.put(230,"Ken");    
          hashMap.put(240,"Mike");    
          hashMap.put(250,"White");   
          hashMap.put(260, "Brown");  
 
          System.out.println(" The original element's list is:");  
         for(Map.Entry m:hashMap.entrySet())  
         {  
            System.out.println(m.getKey()+" "+m.getValue());   
         }  
         System.out.println("The new updated list of elements:");  

         hashMap.replace(240, "Joy");  
         for(Map.Entry m:hashMap .entrySet())  
         {  
            System.out.println(m.getKey()+" "+m.getValue());   
         }  
         System.out.println("The resultant refreshed list of elements:");  
         hm.replace(230, "Rock", "Undertaker");  
         for(Map.Entry m:hashMap.entrySet())  
         {  
            System.out.println(m.getKey()+" "+m.getValue());   
         }   
         System.out.println("The new resultant list of elements:");  
         hashMap.replaceAll((k,v) -> "Bright");  
         for(Map.Entry m:hashMap .entrySet())  
         {  
            System.out.println(m.getKey()+" "+m.getValue());   
         }  
     }  
    }   </pre>
</div>

Example: The distinction between HashSet and HashMap

HashSet only includes values, whereas HashMap only contains entries (key and value).

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>   import java.util.*;
   
    class Laptop {    
    int id;    
    String name,owner,manufacturer;    
    int count;    

    public Laptop(int id, String name, String owner, String manufacturer, int count) {    
        this.id = id;    
        this.name = name;    
        this.owner = owner;    
        this.manufacturer = manufacturer;    
        this. count = count;    
    }    
    }    
    public class CodeHashMap {   
 
    public static void main(String[] args) {    

        //Creating map of Laptops    
        Map<Integer,Laptop> hashMap=new HashMap<Integer,Laptop>();    

        //Creating Laptops    
        Laptop laptopOne=new Laptop(1,"Lenovo","Tyson","Lenovo",2);    
        Laptop laptopTwo=new Laptop(2,"HP","James","HP",1);    
        Laptop laptopThree=new Laptop(3,"DELL","Green","DELL",3);   
 
        //Adding Laptops  to a hash map   
        hashMap.put(1,laptopOne);  
        hashMap.put(2,laptopTwo);  
        hashMap.put(3,laptopThree);  
          
        //how to traverse the map  
        for(Map.Entry<Integer, Laptop> entry:map.entrySet()){    

            int key=entry.getKey();  
            Laptop laptop=entry.getValue();  
            System.out.println(key+" Details:");  
            System.out.println(laptop .id+" "+laptop.name+" "+laptop.owner+" "+laptop.manufacturer+" "+laptop.count);   
        }    
    }    
    }    </pre>
</div>

Conclusion

The Map interface in Java is implemented by the HashMap class, which allows us to store key-value pairs with unique keys. Attempts to insert a duplicate key cause the corresponding key’s element to be overwritten. The key index makes updating, removing, and other operations easier.

The HashMap class is found in java.util package. In Java, HashMap is similar to Hashtable. However, it is not synchronized. It also allows us to store null elements, although only one null key should be used. HashMap<K, V> has been used since Java 5, where K stands for key and V stands for value. It implements the Map interface and inherits the AbstractMap class.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *