Write a Java program to how to use replace() method in HashMap


This Java program demonstrates the use of the HashMap.replace() method to update the value of an existing key-value pair in a HashMap. Here's a brief explanation of the program:

  • We create a HashMap h with integer keys and string values.
  • We add some key-value pairs to the HashMap using the put() method.
  • We use a for-each loop to iterate through the key-value pairs in the HashMap and print them to the console.
  • We call the replace() method on the HashMap object h to update the value associated with key 1002 to "Vijay".
  • We use a for-each loop again to iterate through the key-value pairs in the updated HashMap and print them to the console.

Source Code

import java.util.*;
public class Replace_Method
{
	public static void main(String args[])
	{
		HashMap<Integer,String> h =new HashMap<>();
		h.put(1000,"Sam");
		h.put(1001,"Sathish");
		h.put(1002,"Kumar");
		h.put(1003,"Ram"); 
		h.put(1004,"Pooja");
		for(Map.Entry e : h.entrySet())
		{
			System.out.println("Key : "+ e.getKey()+" || Value : "+e.getValue());
		}		
 
		//Replace the value of key-value pair
		h.replace(1002, "Vijay");
 
		System.out.println("\nAfter Replace the key-value pair elements in HashMap .. \n");
		for(Map.Entry e : h.entrySet())
		{
			System.out.println("Key : "+ e.getKey()+" || Value : "+e.getValue());
		}
	}
}

Output

Key : 1000 || Value : Sam
Key : 1001 || Value : Sathish
Key : 1002 || Value : Kumar
Key : 1003 || Value : Ram
Key : 1004 || Value : Pooja

After Replace the key-value pair elements in HashMap ..

Key : 1000 || Value : Sam
Key : 1001 || Value : Sathish
Key : 1002 || Value : Vijay
Key : 1003 || Value : Ram
Key : 1004 || Value : Pooja