Java TreeSet pollFirst() pollLast() Methods Tutorial

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

What is Java TreeSet pollFirst() Method?

The Java TreeSet pollFirst() method is used to get the first element (the lowest element) of a TreeSet 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 TreeSet object that this method is calling with.

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

pollFirst() Method Exceptions:

The method does not throw an exception.

Example: using TreeSet 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 TreeSet pollLast() Method?

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

Note: this method removes the last element from the TreeSet 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 TreeSet object.

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

pollLast() Method Exceptions:

The method does not throw an exception.

Example: using TreeSet 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

Leave a Reply