Java Utility Library

Java LinkedHashSet - spliterator() Method



The java.util.LinkedHashSet.spliterator() method is used to create a late-binding and fail-fast spliterator over the elements in this set.

Syntax

public Spliterator<E> spliterator()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

Returns a spliterator over the elements in this set.

Exception

NA.

Example:

In the example below, the java.util.LinkedHashSet.spliterator() method is used to create a spliterator over the elements in the given set.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a linkedhashset
    LinkedHashSet<Integer> MySet = new LinkedHashSet<Integer>();

    //populating the set
    MySet.add(40);
    MySet.add(20);
    MySet.add(10);
    MySet.add(30);

    //creating spliterator object on MySet 
    Spliterator<Integer> splitr = MySet.spliterator(); 

    //display content of MySet using 
    //tryAdvance method
    System.out.print("MySet contains: ");              
    while(splitr.tryAdvance((n) -> System.out.print(n + " ")));   
  }
}

The output of the above code will be:

MySet contains: 40 20 10 30 

Example:

Lets consider another example to learn the concept of spliterator over the elements in the given set.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a linkedhashset
    LinkedHashSet<Integer> MySet = new LinkedHashSet<Integer>();

    //populating the set
    MySet.add(40);
    MySet.add(20);
    MySet.add(10);
    MySet.add(-30);

    //creating spliterator object on MySet 
    Spliterator<Integer> splitr = MySet.spliterator(); 

    //printing estimateSize of MySet
    System.out.println("Estimated size: " + splitr.estimateSize());  

    //display content of MySet using 
    //forEachRemaining method
    System.out.print("MySet contains: ");               
    splitr.forEachRemaining((n) -> System.out.print(n + " "));
  }
}

The output of the above code will be:

Estimated size: 4
MySet contains: 40 20 10 -30 

❮ Java.util - LinkedHashSet