Java LinkedList forEach() Method
Example
Use a lambda expression in the LinkedList
's forEach()
method to print every 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 performs an action on every item in a list. The action can be defined by a lambda expression that is compatible with the accept()
method of Java's Consumer
interface.
To learn about lambda expressions, see our Java Lambda Expression tutorial.
Syntax
public void forEach(Consumer action)
Parameter Values
Parameter | Description |
---|---|
action | Required. A Consumer object or lambda expression which performs an action on an item. |
Related Pages
Java Lambda Expressions Tutorial
❮ LinkedList Methods