Write a Java program to get the smallest item from the TreeSet collection


The code demonstrates how to find the smallest item in a TreeSet in Java. In the Smallest_Item class, a TreeSet object called num is created to store integers. Integers such as 70, 30, 50, 20, and 60 are added to the num set using the add method.

The num.first() method is used to retrieve the smallest element from the num set. The first method returns the first (smallest) element in the set according to its natural order without removing it, and the smallest element is stored in the large variable.

The System.out.println statement is used to print the smallest item in the num set, which is displayed as "Smallest Item in TreeSet : {value}" where {value} represents the actual smallest element in the set.

Source Code

import java.io.*;
import java.util.*;
public class Smallest_Item
{
	public static void main(String args[])
	{
		TreeSet <Integer> num = new TreeSet <Integer>();
		num.add(70);
		num.add(30);
		num.add(50);
		num.add(20);
		num.add(60);
		int large = num.first();
		System.out.println("Smallest Item in TreeSet : " + large);
	}
}

Output

Smallest Item in TreeSet : 20