Java TreeSet - pollFirst() Method
The java.util.TreeSet.pollFirst() method is used to retrieve and remove the first (lowest) element of the set. Every removal of element results into reducing the set size by one unless the set is empty. The method returns null, if the set is empty.
Syntax
public E pollFirst()
Here, E is the type of element maintained by the container.
Parameters
No parameter is required.
Return Value
Returns the first element, or null if this set is empty.
Exception
NA.
Example:
In the example below, the java.util.TreeSet.pollFirst() method is used to retrieve and remove the lowest element of the given set.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a treeset TreeSet<Integer> MySet = new TreeSet<Integer>(); //populating the set MySet.add(30); MySet.add(20); MySet.add(10); //printing the set System.out.println("MySet contains: " + MySet); //deleting first (lowest) element while(MySet.size() != 0) { System.out.println(MySet.pollFirst() + " is deleted from set."); } } }
The output of the above code will be:
MySet contains: [10, 20, 30] 10 is deleted from set. 20 is deleted from set. 30 is deleted from set.
❮ Java.util - TreeSet