Remove highest element in Java TreeSet

Java 8Object Oriented ProgrammingProgramming

To remove the highest element, use the pollLast() 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 highest element −

tSet.pollLast()

The following is an example to remove highest 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 Highest Value: "+tSet.pollLast());
      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 Highest Value: 88
Updated TreeSet elements...
12
56
78
raja
Published on 11-Jan-2019 10:58:48
Advertisements