Java - Iterate all map entries using its forEach method

Introduction

forEach(BiConsumer<? super K,? super V> action) method from the Map interface can iterate over all entries in the map.

The method takes a BiConsumer instance whose first argument is the key and second argument is the value for the current entry in the map.

Demo

import java.util.HashMap;
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    map.put("XML", "(342)113-1234");
    map.put("Javascript", "(245)890-2345");
    map.put("Json", "(205)678-3456");
    map.put("Java", "(205)678-3456");

    // Use the forEach() method of the Map interface
    map.forEach((String key, String value) -> {
      System.out.println("key=" + key + ", value=" + value);
    });/*from  w  w w. j  ava2 s  .c  o m*/

  }
}

Result

Related Topic