Queue is a concept of Linear Data Structure that follows the concept of FIFO(First In First Out). Queues are majorly used to maintain the order of the elements to which they are added. In this article, we will learn to perform Queue Iteration in Java.
Queue Iteration Program in Java
Syntax with Examples
Iterator<String> it = queue.iterator();
while (it.hasNext()) {
// print elements
}
Below is the program for Queue Iteration in Java:
Java
// Java Program demonstrating // Queue Iteration import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
// Driver Class public class Gfg {
// Main function
public static void main(String[] args) {
// Iterating Queue
Queue<String> studentQueue = new LinkedList<>();
// Inserting element in Queue
studentQueue.add( "Shivansh" );
studentQueue.add( "Sohan" );
studentQueue.add( "Mohan" );
studentQueue.add( "Shivam" );
studentQueue.add( "Radha" );
studentQueue.add( "Rakesh" );
// Initialising Iterator
Iterator<String> studentQueueIterator = studentQueue.iterator();
// Iterating Queue
while (studentQueueIterator.hasNext()) {
String name = studentQueueIterator.next();
System.out.println(name);
}
}
} |
Output
Shivansh Sohan Mohan Shivam Radha Rakesh