Java: Enhanced for-each over a Map with forEach

Map.forEach takes a BiConsumer of key and value for concise iteration.

Code
Map<String, Integer> ages = new LinkedHashMap<>();
ages.put("Ava", 30); ages.put("Ben", 25);
ages.forEach((name, age) -> System.out.println(name + " is " + age));
Output
Ava is 30
Ben is 25
Advertisement

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