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.
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.
23 32 45 63
Program 2: Program to demonstrate forEach() method on ArrayList which contains list of Students Names.
list of Students: Student Name is Ram Student Name is Mohan Student Name is Sohan Student Name is Rabi
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- foreach() loop vs Stream foreach() vs Parallel Stream foreach()
- ArrayList of ArrayList in Java
- Stream forEach() method in Java with examples
- IntStream forEach() method in Java
- DoubleStream forEach() method in Java
- LongStream forEach() method in Java
- Iterable forEach() method in Java with Examples
- ArrayDeque forEach() method in Java
- Vector forEach() method in Java
- HashTable forEach() method in Java with Examples
- LinkedTransferQueue forEach() method in Java with Examples
- LinkedBlockingDeque forEach() method in Java with Examples
- CopyOnWriteArraySet forEach() method in Java with Examples
- CopyOnWriteArrayList forEach() method in Java with Examples
- Properties forEach(BiConsumer) method in Java with Examples
- HashMap forEach(BiConsumer) method in Java with Examples
- Foreach in C++ and Java
- Iterator vs Foreach In Java
- Flatten a Stream of Lists in Java using forEach loop
- Flatten a Stream of Arrays in Java using forEach loop
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.