What is the NavigableSet.pollLast() method in Java?

The NavigableSet.pollLast() method is present in the NavigableSet interface inside the java.util package. The pollLast() method is used to retrieve and remove the last element from the set and as the set is always in sorted format, it leads to the removal of the largest element in the set.

When we add the elements in the NavigableSet, they get stored in a sorted form. If the NavigableSet is of string type, the elements get stored in lexical order irrespective of string length.

Parameter

The NavigableSet.pollLast() does not accept any parameters.

Return value

The NavigableSet.pollLast() method returns the last element in the set.

If the set is empty, it returns null.

Code

Let’s now have a look at the code below.

import java.util.NavigableSet;
import java.util.TreeSet;
class Main
{
public static void main(String[] args)
{
NavigableSet<Integer> s = new TreeSet<Integer>();
s.add(6);
s.add(8);
s.add(5);
s.add(3);
s.add(9);
s.add(10);
s.add(3);
System.out.println("The removed element from the NavigableSet after using NavigableSet.pollLast() is: " + s.pollLast());
}
}

Explanation

  • In lines 1 and 2, we import the required packages and classes.

  • In line 4 we make a Main class.

  • In line 6, we make a main() function.

  • In line 8, we create a TreeSet of Integer type.

  • From lines 10 to 16, we add the elements into the NavigableSet by using the add() method.

  • In line 18, we use the NavigableSet.pollLast() method and display the removed value from the set with a message.

So, this is the way to use the NavigableSet.pollLast() method in Java.