Write a Java Program to Update value of HashMap using key

Java Program to Update value of HashMap using key

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Update value of HashMap using key
Java Program to Update value of HashMap using key

Write a Java Program to Update value of HashMap using key

PROGRAM: Java Program to Update value of HashMap using key

/*Java Program to Update value of HashMap using key*/

1: Update value of HashMap using put()

import java.util.HashMap;

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

HashMap<String, Integer> numbers = new HashMap<>();
numbers.put(“First”, 1);
numbers.put(“Second”, 2);
numbers.put(“Third”, 3);
System.out.println(“HashMap: ” + numbers);

// return the value of key Second
int value = numbers.get(“Second”);

// update the value
value = value * value;

// insert the updated value to the HashMap
numbers.put(“Second”, value);
System.out.println(“HashMap with updated value: ” + numbers);
}
}

2: Update value of HashMap using computeIfPresent()

import java.util.HashMap;

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

HashMap<String, Integer> numbers = new HashMap<>();
numbers.put(“First”, 1);
numbers.put(“Second”, 2);
System.out.println(“HashMap: ” + numbers);

// update the value of Second
// Using computeIfPresent()
numbers.computeIfPresent(“Second”, (key, oldValue) -> oldValue * 2);
System.out.println(“HashMap with updated value: ” + numbers);

}
}

3: Update value of Hashmap using merge()

import java.util.HashMap;

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

HashMap<String, Integer> numbers = new HashMap<>();
numbers.put(“First”, 1);
numbers.put(“Second”, 2);
System.out.println(“HashMap: ” + numbers);

// update the value of First
// Using the merge() method
numbers.merge(“First”, 4, (oldValue, newValue) -> oldValue + newValue);
System.out.println(“HashMap with updated value: ” + numbers);
}
}



Leave a Reply

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