The forEach() method of ArrayList used to perform the certain operation for each element in ArrayList. This method traverses each element of the Iterable of ArrayList until all elements have been Processed by the method or an exception is raised. The operation is performed in the order of iteration if that order is specified by the method. Exceptions thrown by the Operation are passed to the caller.
Until and unless an overriding class has specified a concurrent modification policy, the operation cannot modify the underlying source of elements so we can say that behavior of this method is unspecified.
Retrieving Elements from Collection in Java.
Syntax:
public void forEach(Consumer<? super E> action)
Parameter: This method takes a parameter action which represents the action to be performed for each element.
Returns: This method does not returns anything.
Exception: This method throws NullPointerException if the specified action is null.
Below programs illustrate forEach() method of ArrayList:
Program 1: Program to demonstrate forEach() method on ArrayList which contains a list of Numbers.
import java.util.*;
public class GFG {
public static void main(String[] args)
{
ArrayList<Integer> Numbers = new ArrayList<Integer>();
Numbers.add( 23 );
Numbers.add( 32 );
Numbers.add( 45 );
Numbers.add( 63 );
Numbers.forEach((n) -> System.out.println(n));
}
}
|
Program 2: Program to demonstrate forEach() method on ArrayList which contains list of Students Names.
import java.util.*;
public class GFG {
public static void main(String[] args)
{
ArrayList<String> students = new ArrayList<String>();
students.add( "Ram" );
students.add( "Mohan" );
students.add( "Sohan" );
students.add( "Rabi" );
System.out.println( "list of Students:" );
students.forEach((n) -> print(n));
}
public static void print(String n)
{
System.out.println( "Student Name is " + n);
}
}
|
Output:
list of Students:
Student Name is Ram
Student Name is Mohan
Student Name is Sohan
Student Name is Rabi
Reference: https://docs.oracle.com/javase/10/docs/api/java/util/ArrayList.html#forEach(java.util.function.Consumer)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
26 Nov, 2018
Like Article
Save Article