Java TreeSet pollLast() Example

The pollFirst() method of java.util.TreeSet class retrieves and removes the first (lowest) element, or returns null if this set is empty whereas pollLast() method retrieves and removes the last (highest) element, or returns null if this set is empty.

Signature

public E pollLast()

This method retrieves and removes the last (highest) element, or returns null if this set is empty.

Example

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

import java.util.TreeSet;

public class PollLastMethodTreeSetExample 
{
    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 pollLast()**");
        //Print the element of the treeset
        for(String val : treeSet1)
        {
            System.out.println(val);
        }
        
        //get the Last element of the treeset
        System.out.println("Last element of the treeset is : "+treeSet1.pollLast());
        
        System.out.println("**Elements of the TreeSet after pollLast()**");
        //Print the element of the treeset
        for(String val : treeSet1)
        {
            System.out.println(val);
        }
    } 
}

Output

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

Leave a Reply

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