 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to get the lowest and highest value in TreeSet
In this article, we will learn how to find the lowest and highest values in a TreeSet in Java. The TreeSet class, part of the java.util package, automatically sorts its elements in natural order. We will use the first() and last() methods of the TreeSet class to retrieve the smallest and largest elements, respectively
Problem Statement
 
 Write a Java program to get the lowest and highest value in TreeSet.
Input
50,100,150,200,250,300,400,500,800,1000
Output
TreeSet Lowest value = 50
TreeSet Highest value = 1000
Steps to get the lowest and highest value in TreeSet
Following are the steps to get the lowest and highest value in TreeSet ?
- First import the TreeSet class from java.util package.
- Then we will initialize TreeSet to store integer values.
- Add values in the TreeSet.
- Retrieve the highest and the lowest values.
- Finally print the values
Java program to get the lowest and highest value in TreeSet
Below is the Java program to get the lowest and highest value in TreeSet ?
import java.util.TreeSet; public class Demo { public static void main(String[] args) { TreeSet<Integer> treeSet = new TreeSet<Integer>(); treeSet.add(50); treeSet.add(100); treeSet.add(150); treeSet.add(200); treeSet.add(250); treeSet.add(300); treeSet.add(400); treeSet.add(500); treeSet.add(800); treeSet.add(1000); System.out.println("TreeSet Lowest value = " + treeSet.first()); System.out.println("TreeSet Highest value = " + treeSet.last()); } } Output
TreeSet Lowest value = 50 TreeSet Highest value = 1000
Code Explanation
In the above Java program, we import the TreeSet class from the java.util package. We create a TreeSet of integers and add values using the add() method. The TreeSet stores these elements in increasing (ascending) order. We then use the first() method to get the smallest value and the last() method to get the largest value, printing both to the console. This demonstrates how to manage and retrieve ordered data using TreeSet.
