Map GetOrDefault Compute Idioms

Replace null-check ladders on Maps with getOrDefault, computeIfAbsent, and merge so lookup logic reads as one declarative call.

JavaData Integrity

Code

snippet
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapIdioms {

    public static void main(String[] args) {
        Map<String, Integer> counts = new HashMap<>();
        List<String> words = List.of("alpha", "beta", "alpha", "gamma", "beta", "alpha");

        // merge:缺省 1、存在即累加——两参数解决计数
        for (String word : words) {
            counts.merge(word, 1, Integer::sum);
        }
        System.out.println(counts);

        // computeIfAbsent:按需构建集合容器
        Map<Character, List<String>> byFirst = new HashMap<>();
        for (String word : words) {
            byFirst.computeIfAbsent(word.charAt(0), k -> new java.util.ArrayList<>()).add(word);
        }
        System.out.println(byFirst);

        // getOrDefault:缺席时给默认值而不是 null
        System.out.println("delta count = " + counts.getOrDefault("delta", 0));
    }
}

Inside the snippet

Map GetOrDefault Compute Idioms reduces to the class MapIdioms and the function main.

Repetition is confined to for (String word : words) — the rest of the file is straight-line.

Using it

Running the file prints labeled results such as delta count = — each operation’s effect is visible in the output.

Key statements

byFirst.computeIfAbsent(word.charAt(0), k -> new java.util.ArrayList<>()).add(word);
List<String> words = List.of("alpha", "beta", "alpha", "gamma", "beta", "alpha");
Map<Character, List<String>> byFirst = new HashMap<>();

Interactive Tools for This Topic

FAQ

What does Map GetOrDefault Compute Idioms print when run?
Invoke the file as-is — the `delta count =` prefixes identify which step printed each line.