1. Introduction

The TreeSet class in Java is a member of the Java Collections Framework and is present in java.util package. It extends AbstractSet and implements the NavigableSet interface. The unique feature of a TreeSet is that it stores its elements in a sorted manner, either in their natural order or based on a provided comparator. Let’s explore how to create a TreeSet in Java.

2. Program Steps

1. Import necessary packages.

2. Create a TreeSet and populate it with elements.

3. Display the elements of the TreeSet to confirm they’re in order.

3. Code Program

import java.util.TreeSet;

public class CreateTreeSet {

    public static void main(String[] args) {

        // Step 2: Create a TreeSet and populate it with elements
        TreeSet<String> treeSet = new TreeSet<>();
        treeSet.add("Zebra");
        treeSet.add("Apple");
        treeSet.add("Mango");
        treeSet.add("Banana");

        // Step 3: Display the elements of the TreeSet
        System.out.println("Elements of the TreeSet:");
        for(String fruit : treeSet) {
            System.out.println(fruit);
        }
    }
}

Output:

Elements of the TreeSet:
Apple
Banana
Mango
Zebra

4. Step By Step Explanation

Step 1: The required package java.util is imported to utilize the TreeSet class.

Step 2: A TreeSet is instantiated and populated using the add method. Elements are added in a random order to demonstrate the ordering capability of the TreeSet.

Step 3: We iterate over the TreeSet using an enhanced for loop (for-each loop) and display each element. As can be seen in the output, even though the items were added in a random order, they are displayed in their natural order (alphabetical, in this case).