Java TreeSet pollFirst() Example

In our previous article we have learnt about first() method of java.util.TreeSet class which will get us the first element(head) of the set whereas pollFirst() method retrieves and removes the first (lowest) element, or returns null if this set is empty.

Signature

public E pollFirst()

This method retrieves and removes the first element of the set and will return null if the list is empty.

Example

The following example shows the usage of java.util.TreeSet.pollFirst() method.

import java.util.TreeSet;

public class PollFirstMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // create an empty TreeSet
        TreeSet  treeSet1 = new TreeSet();
        
        // use add() method to add elements to the TreeSet
        treeSet1.add("Element1");
        treeSet1.add("Element2");
        treeSet1.add("Element3");
        treeSet1.add("Element4");
        treeSet1.add("Element5");
        
        System.out.println("**Elements of the TreeSet before pollFirst()**");
        //Print the element of the treeset
        for(String val : treeSet1)
        {
            System.out.println(val);
        }
        
        //get the first element of the treeset
        System.out.println("First element of the treeset is : "+treeSet1.pollFirst());
        
        System.out.println("**Elements of the TreeSet after pollFirst()**");
        //Print the element of the treeset
        for(String val : treeSet1)
        {
            System.out.println(val);
        }
    } 
}

Output

**Elements of the TreeSet before pollFirst()**
Element1
Element2
Element3
Element4
Element5
First element of the treeset is : Element1
**Elements of the TreeSet after pollFirst()**
Element2
Element3
Element4
Element5

Leave a Reply

Your email address will not be published. Required fields are marked *