VOOZH about

URL: https://www.geeksforgeeks.org/java/java-util-linkedlist-poll-pollfirst-polllast-examples-java/

⇱ Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java

Last Updated : 10 Dec, 2018
Java's Linked list class offers a function that allows a "Queue Based" working called poll(). This function not only returns deletes the first element, but also displays them while being deleted and hence can have a lot of usage in daily life problems and competitive programming as well. There are 3 variants of poll(), all three are discussed in this article. 1. poll() : This method retrieves and removes the head (first element) of this list.
Declaration : 
 public E poll()
Return Value : 
 This method returns the first element of this list, or null if this list is empty.
Output :
The initial Linked List is : [Geeks, 4, Geeks, 8]
Head element of the list is : Geeks
Linked List after removal using poll() : [4, Geeks, 8]

2. pollFirst() : This method retrieves and removes the first element of this list, or returns null if this list is empty.
Declaration : 
 public E pollFirst()
Return Value : 
 This method returns the first element of this list, or null if this list is empty
Output :
The initial Linked List is : [Geeks, 4, Geeks, 8]
Head element of the list is : Geeks
Linked List after removal using pollFirst() : [4, Geeks, 8]

3. pollLast() : This method retrieves and removes the last element of this list, or returns null if this list is empty.
Declaration : 
 public E pollLast()
Return Value : 
 This method returns the last element of this list, or null if this list is empty.
Output :
The initial Linked List is : [Geeks, 4, Geeks, 8]
Tail element of the list is : 8
Linked List after removal using pollLast() : [Geeks, 4, Geeks]

Practical Application : This function has potential usage in the "queue management" systems and also in "1st elimination" games that can be thought of. The former example is discussed below.
Output :
The initial queue is : [Astha, Shambhavi, Nikhil, Manjeet]
The order of exit is : Astha <-- Shambhavi <-- Nikhil <-- Manjeet <-- 
Comment