Remove lowest element in Java TreeSet

Java 8Object Oriented ProgrammingProgramming

To remove the lowest element, use the pollFirst() method.

Create a TreeSet and add elements to it −

TreeSet<String> tSet = new TreeSet<String>();
tSet.add("78");
tSet.add("56");
tSet.add("88");
tSet.add("12");

Now, remove the lowest element −

tSet.pollFirst()

The following is an example to remove lowest element in Java TreeSet −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]){
      TreeSet<String> tSet = new TreeSet<String>();
      tSet.add("78");
      tSet.add("56");
      tSet.add("88");
      tSet.add("12");
      System.out.println("TreeSet elements...");
      Iterator<String> i = tSet.iterator();
      while(i.hasNext()){
         System.out.println(i.next());
      }
      System.out.println("Removing Lowest Value: "+tSet.pollFirst());
      System.out.println("Updated TreeSet elements...");
      i = tSet.iterator();
      while(i.hasNext()){
         System.out.println(i.next());
      }
   }
}

Output

TreeSet elements...
12
56
78
88
Removing Lowest Value: 12
Updated TreeSet elements...
56
78
88
raja
Published on 11-Jan-2019 06:26:01
Advertisements