Write a Java program to access elements from TreeSet Collection using spliterator() method


This is a Java program that demonstrates how to use the spliterator() method of the TreeSet class to iterate over the elements of a set.

The program first creates a TreeSet object called num, which is a collection of unique elements sorted in ascending order. It adds seven integers to the set using the add() method.

Then, the program creates a spliterator splt for the num set using the spliterator() method. It uses the forEachRemaining() method with a lambda expression to iterate through the elements of the set and print them.

Source Code

import java.io.*;
import java.util.*;
public class Spliterator_Method
{
	public static void main(String args[])
	{
		TreeSet <Integer> num = new TreeSet <Integer>();
		num.add(45);
		num.add(30);
		num.add(50);
		num.add(25);
		num.add(60);
		num.add(35);
		num.add(40);
 
		Spliterator <Integer> splt = num.spliterator();
		System.out.println("Elements of TreeSet .. ");
		splt.forEachRemaining(System.out::println);
	}
}

Output

Elements of TreeSet ..
25
30
35
40
45
50
60