
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between Peek, Poll, and Remove Methods of Queue Interface in Java
This represents a collection that is indented to hold data before processing. It is an arrangement of the type First-In-First-Out (FIFO). The first element put in the queue is the first element taken out from it.
The peek() method
The peek() method returns the object at the top of the current queue, without removing it. If the queue is empty this method returns null.
Example
import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String args[]) { Queue<String> queue = new LinkedList<String>(); queue.add("Java"); queue.add("JavaFX"); queue.add("OpenCV"); queue.add("Coffee Script"); queue.add("HBase"); System.out.println("Element at the top of the queue: "+queue.peek()); Iterator<String> it = queue.iterator(); System.out.println("Contents of the queue: "); while(it.hasNext()) { System.out.println(it.next()); } } }
Output
Element at the top of the queue: Java Contents of the queue: Java JavaFX OpenCV Coffee Script Hbase
The poll() method
The poll() method of the Queue interface returns the object at the top of the current queue and removes it. If the queue is empty this method returns null.
Example
import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String args[]) { Queue<String> queue = new LinkedList<String>(); queue.add("Java"); queue.add("JavaFX"); queue.add("OpenCV"); queue.add("Coffee Script"); queue.add("HBase"); System.out.println("Element at the top of the queue: "+queue.poll()); Iterator<String> it = queue.iterator(); System.out.println("Contents of the queue: "); while(it.hasNext()) { System.out.println(it.next()); } } }
Output
Element at the top of the queue: Java Contents of the queue: JavaFX OpenCV Coffee Script HBase
Advertisements