NavigableSet - pollFirst and pollLast example Java Collections

pollFirst(), pollLast() methods of NavigableSet can be used to remove first and last element of the Set respectively. The below program explains the pollFirst() and pollLast()


package examples;

import java.util.NavigableSet;
import java.util.TreeSet;

public class NavigableSetExample {

public static void main(String args[]){
NavigableSet navigableSet = new TreeSet();

navigableSet.add(1);
navigableSet.add(2);

System.out.println("Set : " + navigableSet);

navigableSet.pollFirst();

System.out.println("Set After pollFirst " + navigableSet);

navigableSet.add(3);
navigableSet.add(4);

System.out.println("Set " + navigableSet);

navigableSet.pollLast();

System.out.println("Set after pollLast " +navigableSet);

}

}

Output:


Set : [1, 2]
Set After pollFirst [2]
Set [2, 3, 4]
Set after pollLast [2, 3]

No comments:

Post a Comment

Please Provide your feedback here