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

Given a TreeSet collection, we have to access elements using spliterator() method.
Submitted by Nidhi, on June 08, 2022

Problem Solution:

In this program, we will create a TreeSet collection with integer elements. Then we will access elements from the TreeSet Collection using the spliterator() method.

Program/Source Code:

The source code to access elements from TreeSet Collection using the spliterator() method is given below. The given program is compiled and executed successfully.

Example of TreeSet.spliterator() Method in Java

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

import java.io.*;
import java.util.*;

public class Main {
  public static void main(String args[]) {
    TreeSet < Integer > tree = new TreeSet < Integer > ();

    tree.add(10);
    tree.add(20);
    tree.add(25);
    tree.add(30);
    tree.add(35);
    tree.add(40);

    Spliterator < Integer > splt = tree.spliterator();
    System.out.println("Elements of TreeSet: ");
    splt.forEachRemaining(System.out::println);
  }
}

Output:

Elements of TreeSet: 
10
20
25
30
35
40

Explanation:

In the above program, we imported the "java.util.*", "java.io.*" packages to use the TreeSet class. Here, we created a public class Main.

The Main class contains a main() method. The main() method is the entry point for the program. And, created a TreeSet collection tree and added integer elements using add() method. Then we accessed elements from the TreeSet Collection using the spliterator() method and printed the result.

Java TreeSet Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.