Java Program to get the lowest and highest value in TreeSet

Java 8Object Oriented ProgrammingProgramming

Create a TreeSet first to get the lowest and highest value:

TreeSet<Integer> treeSet = new TreeSet<Integer>();

Add elements to the TreeSet:

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);

Now, get the lowest value and highest value from the above TreeSet, which are 50 and 1000 respectively:

treeSet.first();
treeSet.last();

Example

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
raja
Published on 24-Apr-2019 13:03:54
Advertisements