Java Utility Library

Java TreeSet - spliterator() Method



The java.util.TreeSet.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.TreeSet.spliterator() method is used to create a spliterator over the elements in the given treeset.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treeset
    TreeSet<Integer> MySet = new TreeSet<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: 10 20 30 40 

Example:

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

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treeset
    TreeSet<Integer> MySet = new TreeSet<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: -30 10 20 40 

❮ Java.util - TreeSet