Java program to create a TreeSet collection

Java example to create a TreeSet collection.
Submitted by Nidhi, on June 04, 2022

Problem Solution:

In this program, we will create a TreeSet collection with integer elements. Then we will add elements using add() method and print the created TreeSet.

Program/Source Code:

The source code to create a TreeSet collection is given below. The given program is compiled and executed successfully.

// Java program to create a TreeSet collection

import java.util.*;

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


    System.out.println("TreeSet elements: " + tree);


TreeSet: [10, 20, 30, 40, 50, 60]


In the above program, we imported the "java.util.*", "*" 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 and printed the TreeSet collection tree.

Java TreeSet Programs »

Related Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.