Java Utility Library

Java TreeSet - pollLast() Method



The java.util.TreeSet.pollLast() method is used to retrieve and remove the last (highest) element of the set. Every removal of element results into reducing the set size by one unless the set is empty. The method returns null, if the set is empty.

Syntax

public E pollLast()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

Returns the last element, or null if this set is empty.

Exception

NA.

Example:

In the example below, the java.util.TreeSet.pollLast() method is used to retrieve and remove the last element of the given set.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treeset
    TreeSet<Integer> MySet = new TreeSet<Integer>();

    //populating the set 
    MySet.add(30);
    MySet.add(20);
    MySet.add(10);

    //printing the set
    System.out.println("MySet contains: " + MySet);

    //deleting last (highest) element
    while(MySet.size() != 0) {
      System.out.println(MySet.pollLast() + " is deleted from set.");
   }
  }
}

The output of the above code will be:

MySet contains: [10, 20, 30]
30 is deleted from set.
20 is deleted from set.
10 is deleted from set.

❮ Java.util - TreeSet