computeIfAbsent creates the missing value and returns it, replacing the get-check-put dance that new code should no longer contain.
Map<String, List<String>> byFirstLetter = new TreeMap<>();
for (String name : List.of("Ava", "Ben", "Amit", "Cara", "Bala")) {
byFirstLetter.computeIfAbsent(name.substring(0, 1), k -> new ArrayList<>()).add(name);
}
byFirstLetter.forEach((letter, names) -> System.out.println(letter + " -> " + names));
A -> [Ava, Amit]
B -> [Ben, Bala]
C -> [Cara]
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30