w3resource

Java ArrayList.forEach() Method

public void forEach(Consumer<? super E> action)

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller.

Package: java.util

Java Platform: Java SE 8

Syntax:

forEach(Consumer<? super E> action)

Parameters:

Name Description Type
action The action to be performed for each element  

Return Value:
the element previously at the specified position

Example: ArrayList.forEach Method

The following example creates an ArrayList with a capacity of 50 elements. Four elements are then added to the ArrayList and the ArrayList is trimmed accordingly.

import java.util.*;
import java.util.function.*;

class MyConsumer<T> implements Consumer<T>{
 public void accept(T ctask){
  System.out.println("Processing Task " + ctask);
 }
}


import java.util.*;
import java.util.*;

import java.util.function.*;

class MyConsumer implements Consumer{

 public void accept(T ctask){

  System.out.println("Processing Task " + ctask);

 }

}

public class Main {

   public static void main(String[] args) 

   {

  ArrayList myList;

  MyConsumer mcons;

  myList = new ArrayList<>(50);

  mcons = new MyConsumer();

  myList.add(100);

  myList.add(200);

  myList.add(300);

  myList.add(400);

  myList.forEach(mcons);

 }

}

Output:

F:\java>javac test.java

F:\java>java test
Processing Task 100
Processing Task 200
Processing Task 300
Processing Task 400

 

Previous:subList Method
Next:spliterator



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-tutorial/arraylist/arraylist_foreach.php