Java Learner logo
← Back to all exercises

Maps

Merging HashMap values

Observe how Map.merge mutates entries; type the two numbers printed.

Maps

Merging HashMap values

AdvancedAwaiting attempt

Observe how Map.merge mutates entries; type the two numbers printed.

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        scores.put("data", 2);
        scores.merge("data", 3, Integer::sum);
        scores.merge("api", 5, (oldVal, newVal) -> oldVal - newVal);
        scores.merge("api", 2, Integer::sum);

        System.out.println(scores.get("data"));
        System.out.println(scores.get("api"));
    }
}