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:
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
CopyOnWriteArraySet<Integer> ArrSet
= new CopyOnWriteArraySet<Integer>();
ArrSet.add( 2 );
ArrSet.add( 3 );
ArrSet.add( 4 );
ArrSet.add( 7 );
ArrSet.add( 8 );
System.out.println( "CopyOnWriteArraySet: "
+ ArrSet);
System.out.println( "Traversing this Set: " );
ArrSet.forEach((n) -> System.out.println(n));
}
}
|
Output:
CopyOnWriteArraySet: [2, 3, 4, 7, 8]
Traversing this Set:
2
3
4
7
8
Example 2:
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
CopyOnWriteArraySet<String> ArrSet
= new CopyOnWriteArraySet<String>();
ArrSet.add( "GeeksforGeeks" );
ArrSet.add( "Geeks" );
ArrSet.add( "Computer Science" );
ArrSet.add( "Portal" );
ArrSet.add( "Gfg" );
System.out.println( "CopyOnWriteArraySet: "
+ ArrSet);
System.out.println( "Traversing this Set: " );
ArrSet.forEach((n) -> System.out.println(n));
}
}
|
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-
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!