![]() |
VOOZH | about |
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.
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.
spliterator() Methodpublic Spliterator<E> spliterator()
Return Value: This method returns a Spliterator over the elements in ArrayList.
Spliterator = Splitting + Iterator
Example 2: Here, we will use the spliterator() method to perform Parallel Processing.
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.