Java HashMapforEach() Method
Example
Use theforEach() method to print every entry in the map:
import java.util.HashMap;public class Main { public static void main(String[] args) { HashMap<String, String> capitalCities = new HashMap<String, String>(); capitalCities.put("England", "London"); capitalCities.put("Germany", "Berlin"); capitalCities.put("Norway", "Oslo"); capitalCities.put("USA", "Washington DC"); capitalCities.forEach( (k, v) -> { System.out.println(k + " -> " + v); } ); }}Definition and Usage
TheforEach() method performs an action on every entry in the map. The action can be defined by a lambda expression that is compatible with theaccept() method of Java'sBiConsumer interface.
To learn about lambda expressions, see ourJava Lambda Expression tutorial.
Syntax
public void forEach(BiConsumeraction)Parameter Values
| Parameter | Description |
|---|---|
| action | Required. ABiConsumer object or lambda expression which performs an action on an entry.The first parameter contains the key of an entry and the second parameter contains its value. |
Related Pages
❮ HashMap Methods

