Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java HashMap replace(key, oldValue, newValue) Method
Next article icon

Java HashMap replace(key, oldValue, newValue) Method

Last Updated : 22 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The replace(key, oldValue, newValue) method of the HashMap class in Java is used to conditionally replace the value of a specified key if, and only if, the current value matches the specified old value.

Example 1: This example demonstrates replacing a value only if the key is mapped to the given old value.

Java
// Java program demonstrates the working of replace() import java.util.HashMap;  public class Geeks {     public static void main(String[] args) {                // Create a HashMap         HashMap<Integer, String> hm = new HashMap<>();         hm.put(1, "Geek1");         hm.put(2, "Geek2");         hm.put(3, "Geek3");          System.out.println("Original map: " + hm);          // Replace value for key 2 only          // if the current value is "Geek2"         boolean b = hm.replace(2, "Geek2", "Geek10");          System.out.println("Was value replaced? " + b);         System.out.println("Updated map: " + hm);     } } 

Output
Original map: {1=Geek1, 2=Geek2, 3=Geek3} Was value replaced? true Updated map: {1=Geek1, 2=Geek10, 3=Geek3} 

Syntax of replace(key, oldValue, newValue) Method

boolean replace(K key, V oldValue, V newValue)

Parameters:

  • key: The key whose associated value is to be replaced.
  • oldValue: The expected current value associated with the key.
  • newValue: The new value to associated with the key.

Return Type:

This method returns "true" if the value associated with the key is replaced successfully or return "false" if the key does not exist in the map.

Exception:

  • NullPointerException occurs only if null is used for a key or value in a map that doesn't support null.
  • IllegalArgumentException only applies to certain Map implementations (like some custom implementations or ConcurrentHashMap).

Example 2: This example shows what happens when the old value provided does not match the current value.

Java
// Java program demonstrates mismatched old value import java.util.HashMap;  public class Geeks {     public static void main(String[] args)     {         // Create a HashMap         HashMap<Integer, String> hm = new HashMap<>();         hm.put(1, "Java");         hm.put(2, "C++");         hm.put(3, "Python");          System.out.println("Initial HashMap: " + hm);          // Replace value for key 2          // if old value matches         boolean b = hm.replace(2, "JavaScript", "C#");          System.out.println("Was replacement successful? "                            + b);         System.out.println("Updated HashMap: " + hm);     } } 

Output
Initial HashMap: {1=Java, 2=C++, 3=Python} Was replacement successful? false Updated HashMap: {1=Java, 2=C++, 3=Python} 


Example 3: This example demonstrates that if the key does not exists, the method returns false.

Java
// Java program demonstrates what happens // if the key does not exists import java.util.HashMap;  public class Geeks {     public static void main(String[] args)     {         // Create a HashMap         HashMap<Integer, String> hm = new HashMap<>();         hm.put(1, "Java");         hm.put(2, "C++");          System.out.println("Initial HashMap: " + hm);          // Replace value for key 2          // if old value matches         boolean b = hm.replace(3, "JavaScript", "C#");          System.out.println("Was replacement successful? "                            + b);         System.out.println("Updated HashMap: " + hm);     } } 

Output
Initial HashMap: {1=Java, 2=C++} Was replacement successful? false Updated HashMap: {1=Java, 2=C++} 

Next Article
Java HashMap replace(key, oldValue, newValue) Method

I

iamvineettiwari
Improve
Article Tags :
  • Java
  • Java-Collections
  • Java-Functions
  • Java-HashMap
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

    Java HashMap replace() Method
    The replace() method of the HashMap class in Java is used to replace the value associated with a specific key if the key is already present in the map.Note: If the key does not exist, the method does nothing and the map remains unchanged.Example 1: This example demonstrates replacing the value of an
    3 min read
    Java HashMap putAll() Method
    The putAll() method of the Java HashMap class is used to copy all key-value mappings from another map to the existing map. If a key exists in both maps, its value is updated with the value from the source map. Otherwise, new key-value pairs are added.Example 1: This example demonstrates copying all
    2 min read
    Java HashMap remove() Method
    The remove() method of the Java HashMap class is used to remove a key-value pair from the map based on the given key. If the key is found, the mapping associated with the key is returned, otherwise, it returns null.Example 1: This example demonstrates how to use remove(Object key) to remove a key-va
    3 min read
    HashMap values() Method in Java
    The java.util.HashMap.values() method of HashMap class in Java is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the HashMap. Syntax: Hash_Map.values() Parameters: The method does not accept any parameters. Return Value: The method i
    2 min read
    Java HashMap put() Method
    The put() method of the Java HashMap class is used to add or update the key-value pairs in the map. If the key already exists in the map, the previous value associated with the key is replaced by the new value and If the key does not exist, the new key-value pair is added to the map.Syntax of HashMa
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences