Saturday, November 22, 2025
HomeLanguagesJavaTreeSet pollLast() method in Java with Example

TreeSet pollLast() method in Java with Example

The pollLast() method of Java.util.concurrent.TreeSet is an in-built function in Java which returns retrieves and removes the last (highest) element, or returns null if this set is empty.

Syntax:

public E pollLast()

Return Value: The function returns retrieves and removes the last (highest) element, or returns null if this set is empty.

Below programs illustrate the TreeSet.pollLast() method:

Program 1:




// Java program to demonstrate pollLast()
// method of TreeSet
  
import java.util.*;
  
class TreeSetpollLastExample1 {
    public static void main(String[] args)
    {
        // Creating a set object
        TreeSet<Integer> set
            = new TreeSet<Integer>();
  
        // Adding elements to this set
        for (int i = 10; i <= 50; i += 10)
            set.add(i);
  
        // Printing the content of the set
        System.out.println("Contents of the set: " + set);
  
        // Retrieving and removing Last element of the set
        System.out.println("The Last element of the set: "
                           + set.pollLast());
  
        // Printing the content of the set after pollLast()
        System.out.println("Contents of the set after pollLast: "
                           + set);
    }
}


Output:

Contents of the set: [10, 20, 30, 40, 50]
The Last element of the set: 50
Contents of the set after pollLast: [10, 20, 30, 40]

Program 2:




// Java program to demonstrate pollLast()
// method of TreeSet
  
import java.util.*;
  
class TreeSetpollLastExample2 {
    public static void main(String[] args)
    {
        // Creating a set object
        TreeSet<Integer> set
            = new TreeSet<Integer>();
  
        // Printing the content of the set
        System.out.println("Contents of the set: "
                           + set);
  
        // Retrieving and removing Last element of the set
        System.out.println("The Last element of the set: "
                           + set.pollLast());
    }
}


Output:

Contents of the set: []
The Last element of the set: null
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6784 POSTS0 COMMENTS
Nicole Veronica
11931 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11999 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6863 POSTS0 COMMENTS
Umr Jansen
6848 POSTS0 COMMENTS