Java NavigableSet pollFirst() pollLast() Methods Tutorial

In this section we will learn what the NavigableSet pollFirst() and pollLast() methods are and how to use them in Java.

What is Java NavigableSet pollFirst() Method?

The Java NavigableSet pollFirst() method is used to get the first element (the lowest element) of a NavigableSet object and return that as a result.

Note: the element will be removed from the list as well.

Java pollFirst() Method Syntax:

public E pollFirst()

pollFirst() Method Parameters:

The method does not take an argument.

pollFirst() Method Return Value:

The return value of this method is the first element (the lowest element) of a NavigableSet object that this method is calling with.

Note: if the target NavigableSet object was empty, calling this method will return null instead.

pollFirst() Method Exceptions:

The method does not throw an exception.

Example: using NavigableSet pollFirst() method

import java.util.NavigableSet;
import java.util.TreeSet;
class Main{
    public static void main(String[] args) {
        NavigableSet<Integer> navigate = new TreeSet<>();
        navigate.add(1);
        navigate.add(2);
        navigate.add(3);
        navigate.add(0);
        navigate.add(10);

        System.out.println(navigate.pollFirst());
    }
        
}

Output:

0

What is Java NavigableSet pollLast() Method?

The Java NavigableSet pollLast() method is used to get the last element of a NavigableSet object and return that value as a result.

Note: this method removes the last element from the NavigableSet object as well.

Java pollLast() Method Syntax:

public E pollLast()

pollLast() Method Parameters:

The method does not take an argument.

pollLast() Method Return Value:

The return value of this method is the last element of the target NavigableSet object.

Note: if the NavigableSet is empty, the value null will return instead.

pollLast() Method Exceptions:

The method does not throw an exception.

Example: using NavigableSet pollLast() method

import java.util.NavigableSet;
import java.util.TreeSet;
class Main{
    public static void main(String[] args) {
        NavigableSet<Integer> navigate = new TreeSet<>();
        navigate.add(1);
        navigate.add(2);
        navigate.add(3);
        navigate.add(0);
        navigate.add(10);

        System.out.println(navigate.pollLast());
    }
        
}

Output:

10

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies