Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

forEach()

Example

Utilize the forEach() method to output each 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

The forEach() method executes an action on each entry within the map. This action can be specified using a lambda expression that adheres to Java’s BiConsumer interface’s accept() method.

Syntax

 public void forEach(BiConsumer action)

Parameter Values

Parameter

Description

action

Required: A BiConsumer object or lambda expression that carries out an action on an entry. The first parameter holds the entry’s key, and the second parameter holds its value.