computeIfAbsent inserts a default value only when a key is missing.
Map<String, List<Integer>> groups = new HashMap<>();
int[][] pairs = {{1, 10}, {1, 11}, {2, 20}};
for (int[] p : pairs) {
groups.computeIfAbsent(String.valueOf(p[0]), k -> new ArrayList<>()).add(p[1]);
}
System.out.println(groups);
{1=[10, 11], 2=[20]}
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-26