Java Collection spliterator() with Examples

The spliterator() in Java Collection creates a spliterator over the elements in the collection. In simple words, it’s an iterator that allows you to traverse the elements individually but is specially designed to work in parallel processing scenarios. The difference between Iterator and Spliterator is iterator does not support parallel programming but spliterator supports parallel programming.

Syntax

public Spliterator<E> spliterator();

Here E denotes the type of element stored inside the collection.

Return Value

It returns a spliterator across elements in the collection.

Example 1

In this example, we have used some of the methods of spliterator that we need to understand before we proceed to the example.

  1. spliterator(): It returns a spliterator across the element of the calling collection.
  2. tryAdvance(): It returns a boolean value. It returns true, if there are more elements exist else it returns false.

Java




import java.util.List;
import java.util.ArrayList;
import java.util.Spliterator;
import java.io.*;
  
class GFG {
    public static void main (String[] args) {
              
            List<String> list1 = new ArrayList<String>();
            list1.add("Pen");
            list1.add("Paper");
            list1.add("Rubber");
            list1.add("Pencil");
  
            Spliterator<String> spliterator = list1.spliterator();
  
            System.out.println("The list contains:");
            while(spliterator.tryAdvance((element)->System.out.print(element+" ")));  
    }
}


Output:

The list contains:
Pen Paper Rubber Pencil

Example 2

In this example, we have used spliterator() in Hashset Collection.The same way as above example it traverses through the set and prints the element.

Java




import java.util.HashSet;
import java.util.Spliterator;
import java.io.*;
  
class GFG {
    public static void main (String[] args) {
          
        HashSet<Integer> list1 = new HashSet<Integer>();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        list1.add(4);
        list1.add(5);
        list1.add(6);
  
        Spliterator<Integer> spliterator1 = list1.spliterator();
  
        System.out.println("The collection contains :");
        while(spliterator1.tryAdvance((element)->System.out.print(element+" "))); 
    }
}


Ouput:

The collection contains :
1 2 3 4 5 6


Contact Us