Write a Java program to Get and Remove the largest element from the TreeSet collection


The code demonstrates how to get and remove the largest element from a TreeSet in Java. In the GetRemove_Largest class, a TreeSet object called num is created to store integers. Integers such as 10, 70, 50, 100, 80, 30, 60, 20, 90, and 40 are added to the num set using the add method.

The System.out.println statement is used to print the elements in the num set, which will be displayed in ascending order as TreeSet automatically sorts its elements based on their natural order.

The num.pollLast() method is used to get and remove the largest element from the num set. The pollLast method retrieves and removes the last (largest) element from the set, and the removed element is stored in the item variable.

The System.out.println statement is used again to print the removed item and the updated elements in the num set after the removal. Note that the pollLast method returns null if the set is empty. If you want to retrieve the largest element from the set without removing it, you can use the last method instead.

Source Code

import java.io.*;
import java.util.*;
public class GetRemove_Largest
{
	public static void main(String args[])
	{
		TreeSet <Integer> num = new TreeSet <Integer>();
		num.add(10);
		num.add(70);
		num.add(50);
		num.add(100);
		num.add(80);
		num.add(30);
		num.add(60);
		num.add(20);
		num.add(90);
		num.add(40);
		System.out.println("TreeSet Element : " + num);
 
		int item = num.pollLast();
		System.out.println("Removed Item : " + item);
		System.out.println("TreeSet Element : " + num);
	}
}

Output

TreeSet Element : [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Removed Item : 100
TreeSet Element : [10, 20, 30, 40, 50, 60, 70, 80, 90]