Java program to iterate TreeSet collection in ascending order

Given a TreeSet collection, we have to iterate it in ascending order.
Submitted by Nidhi, on June 05, 2022

Problem Solution:

In this program, we will create a TreeSet collection with integer elements. Then we will use the iterator() method to iterate created TreeSet collection in ascending order.

Program/Source Code:

The source code to iterate the TreeSet collection in ascending order is given below. The given program is compiled and executed successfully.

Example of TreeSet.iterator() Method in Java

// Java program to iterate TreeSet collection 
// in ascending order

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

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

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

    Iterator < Integer > iterator = tree.iterator();

    System.out.println("Elements in ascending order:");

    while (iterator.hasNext()) {
      System.out.println("Value : " + iterator.next());
    }
  }
}

Output:

Elements in ascending order:
Value : 20
Value : 25
Value : 30
Value : 35

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 used the iterator() method to get elements of the TreeSet collection and printed them in ascending order.

Java TreeSet Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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