VOOZH about

URL: https://www.geeksforgeeks.org/java/copyonwritearrayset-foreach-method-in-java-with-examples/

⇱ CopyOnWriteArraySet forEach() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CopyOnWriteArraySet forEach() method in Java with Examples

Last Updated : 11 Jul, 2025
The forEach() method of CopyOnWriteArraySet is an in-built function in Java which is used to traverse each element in this Set. Syntax:
public void forEach (Consumer<E> action)
Parameters: This method takes a parameter action which represents the action to be performed for each element. Return Value: This method does not returns anything. Exceptions: This method throws NullPointerException if the specified action is null. Below program illustrates the forEach() function of CopyOnWriteArraySet class: Example 1:
Output:
CopyOnWriteArraySet: [2, 3, 4, 7, 8]
Traversing this Set: 
2
3
4
7
8
Example 2:
Output:
CopyOnWriteArraySet: [GeeksforGeeks, Geeks, Computer Science, Portal, Gfg]
Traversing this Set: 
GeeksforGeeks
Geeks
Computer Science
Portal
Gfg
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/CopyOnWriteArraySet.html#forEach-java.util.function.Consumer-
Comment