public class ComputeExample {
public static void main(String[] args) {
Map<String, Integer> freq
= new HashMap<>();
String c = "apple";
// First time:
key "apple" is missing, so v is null and it sets value to 1
freq.compute(c, (k, v) -> v == null ? 1 : v + 1);
System.out.println(freq.get("apple")); // Output: 1
// Second time: key "apple" exists with value 1, so it adds 1
to make it 2
freq.compute(c, (k, v) -> v == null ? 1 : v + 1);
System.out.println(freq.get("apple")); // Output: 2
freq.merge(c, 1, Integer::sum);
freq.putIfAbsent(c, 0);
freq.put(c, freq.get(c) + 1);
freq.put(c, freq.getOrDefault(c, 0) + 1);
if (freq.containsKey(c)) {
freq.put(c, freq.get(c) + 1);
} else {
freq.put(c, 1);
}
}
}