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 a lambda expression within the ArrayList’s forEach() method to print each item contained in the list.

import java.util.ArrayList;
public class Main {
 public static void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(9);
    numbers.add(8);
    numbers.add(1);
    numbers.forEach( (n) -> { System.out.println(n); } );
  }
}

Definition and Usage

The forEach() method executes an action on every item within a list, typically defined by a lambda expression compatible with Java’s Consumer interface’s accept() method.

For further understanding of lambda expressions, you can refer to our Java Lambda Expression tutorial.

Syntax

public void forEach(Consumer action)

Parameter Values

Parameter

Description

action

Necessary: Either a Consumer object or a lambda expression that executes an action on each item.