Home »
Java »
Java Programs
Java program to get the largest item from the TreeSet collection
Given a TreeSet collection, we have to get the largest item from it.
Submitted by Nidhi, on June 06, 2022
Problem statement
In this program, we will create a TreeSet collection with integer elements. Then we will find the largest item from the TreeSet collection using the last() method.
Source Code
The source code to get the largest item from the TreeSet collection is given below. The given program is compiled and executed successfully.
Example of TreeSet.last() Method in Java
// Java program to get the largest item from
// TreeSet collection
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]) {
TreeSet < Integer > tree = new TreeSet < Integer > ();
tree.add(30);
tree.add(20);
tree.add(25);
tree.add(10);
int large = tree.last();
System.out.println("Largest item in TreeSet is: " + large);
}
}
Output
Largest item in TreeSet is: 30
Explanation
In the above program, we imported the "java.util.*", "java.io.*" 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. Then we found the largest item from the TreeSet collection using the last() method and printed the result.
Java TreeSet Programs »