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

Introduction

In this shot, we will learn how to use the NavigableSet.pollFirst() and method in Java.

The pollFirst() method

The pollFirst() method is present in the NavigableSet interface inside the java.util package.

The NavigableSet.pollFirst() is used to retrieve and remove the first element from the set.

And as the set is always in sorted format, it leads to the removal of the lowest element in the set.

If the set is empty, it returns null.


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

Parameter

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

Return

The NavigableSet.pollFirst() method return the first element in the set.

Code

Let us 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(17);
System.out.println("The removed element from the NavigableSet after using NavigableSet.pollFirst() is: " + s.pollFirst());
}
}

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.pollFirst() method and displayed the removed value from the set with a message.

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

Free Resources