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


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

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

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

Source Code

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

Output

Largest Item in TreeSet : 70