Mapmap = new HashMap<>(); map.put("John", 25); map.put("Sarah", 28); for (Map.Entry entry : map.entrySet()) { if (entry.getKey().equals("John")) { entry.setValue(26); } } System.out.println(map.get("John")); // Output: 26
import java.util.*; public class Main { public static void main(String[] args) { TreeMapIn this example, we create a TreeMap with four entries and then use the setValue() method to update the value for the key "Cherry" from 1200 to 1500. Finally, we print the updated map. This code belongs to the java.util package library.map = new TreeMap<>(); map.put("Apple",1000); map.put("Banana",800); map.put("Cherry", 1200); map.put("Mango", 500); System.out.println("Before update: " + map); for (Map.Entry entry : map.entrySet()) { if (entry.getKey().equals("Cherry")) { entry.setValue(1500); } } System.out.println("After update: " + map); } }