Sunday, May 15, 2022

Queue poll() method in Java


The poll() method of Queue Interface returns and removes the element at the front end of the container. It deletes the element in the container. 


The method does not throws an exception when the Queue is empty, it returns null instead.


Syntax: E poll();


Below program illustrate poll() method of Queue:


package com.practice;

import java.util.LinkedList;
import java.util.Queue;

public class QueuePollMethod {

public static void main(String[] args)
throws IllegalStateException
{

// create object of Queue
Queue<Integer> queue = new LinkedList<Integer>();

// Add numbers to end of Queue
queue.add(123);
queue.add(456);
queue.add(789);

// print queue
System.out.println("Queue: " + queue);

// print head and deletes the head
System.out.println("Queue's head: " + queue.poll());

// print head and deleted the head
System.out.println("Queue's head: " + queue.poll());

// print head and deleted the head
System.out.println("Queue's head: " + queue.poll());

// print head and deleted the head. Queue is enpty now hence it returns null
System.out.println("Queue's head: " + queue.poll());
}
}


Output:

queue poll() in java



Explanation:

Queue has "123", "456", "789"

First queue.poll() returns - 123

Now queue has "456", "789"

Second queue.poll() returns - 456

Now queue has  "789"

Third queue.poll() returns - 789

Queue is empty now


Fourth queue.poll() returns - null ( as queue is empty). It will not throw any exception.

Happy Coding!


No comments:

Post a Comment

ElasticSearch vs Apache SolrCloud

  Elasticsearch and Apache SolrCloud are both powerful, distributed search engines built on top of Apache Lucene. Both Elasticsearch and S...