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 LinkedList’s forEach() method to print each item in the list.

import java.util.LinkedList;

public class Main { public static void main(String[] args) {

LinkedList<Integer> numbers = new LinkedList<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 each item within a list. This action can be defined by a lambda expression that conforms to the accept() method of Java’s Consumer interface.

Syntax

public void forEach(Consumer action)

Parameter Values

Parameter

Description

action

Mandatory. A Consumer object or lambda expression responsible for executing an action on each item.