Java ArrayList spliterator() Method (original) (raw)

Last Updated : 15 Dec, 2024

The **spliterator() method in Java is used to iterate over the elements of an ArrayList. It provides a more efficient way to traverse the collection specially with parallel processing. This method is part of Java 8 and later.

**Example 1: Here, we will use the **spliterator() method **to loop through elements in the ArrayList.

Java `

// loop through elements in an // ArrayList using spliterator() import java.util.ArrayList; import java.util.Spliterator;

public class GFG { public static void main(String[] args) {

    // Create an ArrayList
    ArrayList<String> al = new ArrayList<>();
    al.add("Apple");
    al.add("Mango");
    al.add("Banana");
    al.add("Grapes");

    // Get Spliterator
    Spliterator<String> si = al.spliterator();

    // Loop through elements
    si.forEachRemaining(System.out::println);
}

}

`

Output

Apple Mango Banana Grapes

**Explanation: In the above example, we have used the **forEachRemaining() method of Spliterator to sequentially loop through all elements in an ArrayList.

Syntax of spliterator() Method

public Spliterator spliterator()

**Return Value: This method returns a **Spliterator over the elements in ArrayList.

**Points to Remember:

Spliterator = Splitting + Iterator

**Example 2: Here, we will use the **spliterator() method **to perform Parallel Processing.

Java `

// Parallel Processing with splititerator() import java.util.ArrayList; import java.util.Spliterator;

public class GFG { public static void main(String[] args) {

    // Create an ArrayList and add numbers
    ArrayList<Integer> n = new ArrayList<>();
    for (int i = 1; i <= 5; i++) {
        n.add(i);
    }

    // Get a Spliterator and split it 
    // for parallel processing
    Spliterator<Integer> si = n.spliterator();
    Spliterator<Integer> si1 = si.trySplit();

    // Parallel processing
    si1.forEachRemaining(num -> System.out.println("Thread 1: " + num));
    si.forEachRemaining(num -> System.out.println("Thread 2: " + num));
}

}

`

Output

Thread 1: 1 Thread 1: 2 Thread 2: 3 Thread 2: 4 Thread 2: 5

**Explanation: The above example demonstrates **parallel processing using **Spliterator by splitting an ArrayList into two parts. The first Spliterator processes one part in “Thread 1,” and the second processes the remaining part in “Thread 2.”

**Note: The actual output might vary depending on the JVM, as the division of elements between threads is not guaranteed to be exactly the same every time.