• Java Data Structures Tutorial

Printing the elements of the Queue



You can print the contents of the queue directly, using the println() method.

System.out.println(queue)

Besides that, the Queue also provides iterator() method which returns the iterator of the current queue. Using this you can print the contents of the it one by one.

Example

import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;

public class PrintingElements {
   public static void main(String args[]) {
         
      // Create priority queue
      Queue <String>  prQueue = new PriorityQueue <String> () ; 
      
      // Adding elements
      prQueue.add("JavaFX");
      prQueue.add("Java");
      prQueue.add("HBase");
      prQueue.add("Flume");
      prQueue.add("Neo4J");

      Iterator iT = prQueue.iterator();
      System.out.println("Contents of the queue are :");
      
      while(iT.hasNext()) {
         System.out.println(iT.next());  
      }
   }
}

Output

Contents of the queue are :
Flume
HBase
Java
JavaFX
Neo4J
Advertisements