Get Lowest and Highest Value in TreeSet in Java



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.

Updated on: 2024-08-21T00:03:22+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements