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 merge() Method
Next article icon

Java HashMap merge() Method

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

In Java, the merge() method of the HashMap class is used to either add new key-value pairs or update the existing one in the map by merging values using a specified function.

  • If the key is not present in the map, the merge() method adds the key with the given value.
  • If the key already exists in the map, the method uses a BiFunction to combine the old value and the new value into one and then updates the key with the combined value.

Note: It either adds the new entry or updates an existing one by merging values together

Example 1: The below Java program demonstrates the use of merge() method to add new key-value pairs and update the existing ones by combining old and new values using the Lambda function.

Java
// Java program to demonstrate adding and updating  // key-value pairs using merge() import java.util.HashMap;  public class Main {     public static void main(String[] args)     {         // creating a HashMap to store key-value pairs         HashMap<String, Integer> hm = new HashMap<>();         hm.put("A", 10);         hm.put("B", 20);          // use merge() for a key that          // is not present in the map         hm.merge("C", 30,             (oldValue, newValue) -> oldValue + newValue);          // use merge() for a key that          // is already present in the map         hm.merge("A", 15,             (oldValue, newValue) -> oldValue + newValue);          System.out.println(hm);     } } 

Output
{A=25, B=20, C=30} 

Syntax of HashMap merge() Method

default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)

Parameters: This method takes three parameters.

  • Key: The key whose value is to be merged
  • Value: The new value to be merged with the existing one.
  • remappingFunction: It is a function that takes two arguments the current value and the new value and then calculate the new value

Return Type: Return the new value associated with the key or null if the new value is null.

Example 2: The below Java program demonstrates the use of merge() to update the existing value or insert the new key-value pair using a custom BiFunction.

Java
// Java program to demonstrate merging  // string values using merge() import java.util.HashMap;  public class Geeks {     public static void main(String[] args)     {                HashMap<String, String> hm = new HashMap<>();         hm.put("A", "Hello");         hm.put("B", "World");          // use merge() for a key that          // is already present in the map         hm.merge("A", "Java",                 (oldValue,newValue) -> oldValue + " " + newValue);          // use merge() for the key that         // is not present in the map         hm.merge("C", "Programming",             (oldValue, newValue) -> oldValue + newValue);          System.out.println(hm);     } } 

Output
{A=Hello Java, B=World, C=Programming} 

Next Article
Java HashMap merge() Method

V

VincentSimon
Improve
Article Tags :
  • Java
  • Java - util package
  • Java-Functions
  • Java-HashMap
Practice Tags :
  • Java

Similar Reads

    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
    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 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
    HashMap clear() Method in Java
    The clear() method of the HashMap class in Java is used to remove all of the elements or mappings (key-value pairs) from a specified HashMap.Example 2: Here, we will use the clear() method to clear a HashMap of Integer keys and String values. Java// Clearing HashMap of Integer keys // and String val
    2 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
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