Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaCopyOnWriteArraySet forEach() method in Java with Examples

CopyOnWriteArraySet forEach() method in Java with Examples

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:




// Java Program to illustrate the CopyOnWriteArraySet
// forEach() method in Java
  
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create object of CopyOnWriteArraySet
        CopyOnWriteArraySet<Integer> ArrSet
            = new CopyOnWriteArraySet<Integer>();
  
        // Add elements
        ArrSet.add(2);
        ArrSet.add(3);
        ArrSet.add(4);
        ArrSet.add(7);
        ArrSet.add(8);
  
        // print CopyOnWriteArraySet
        System.out.println("CopyOnWriteArraySet: "
                           + ArrSet);
        System.out.println("Traversing this Set: ");
  
        // Traverse this set using forEach() method
        ArrSet.forEach((n) -> System.out.println(n));
    }
}


Output:

CopyOnWriteArraySet: [2, 3, 4, 7, 8]
Traversing this Set: 
2
3
4
7
8

Example 2:




// Java Program to illustrate the CopyOnWriteArraySet
// forEach() method in Java
  
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Create object of CopyOnWriteArraySet
        CopyOnWriteArraySet<String> ArrSet
            = new CopyOnWriteArraySet<String>();
  
        // Add elements
        ArrSet.add("Lazyroar");
        ArrSet.add("Geeks");
        ArrSet.add("Computer Science");
        ArrSet.add("Portal");
        ArrSet.add("Gfg");
  
        // Print CopyOnWriteArraySet
        System.out.println("CopyOnWriteArraySet: "
                           + ArrSet);
        System.out.println("Traversing this Set: ");
  
        // Traverse this set using forEach() method
        ArrSet.forEach((n) -> System.out.println(n));
    }
}


Output:

CopyOnWriteArraySet: [Lazyroar, Geeks, Computer Science, Portal, Gfg]
Traversing this Set: 
Lazyroar
Geeks
Computer Science
Portal
Gfg

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/CopyOnWriteArraySet.html#forEach-java.util.function.Consumer-

RELATED ARTICLES

Most Popular

Recent Comments