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
This 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 peek() 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