How to Iterate over a Queue in Java?
Last Updated :
25 Jan, 2024
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
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class Gfg {
public static void main(String[] args) {
Queue<String> studentQueue = new LinkedList<>();
studentQueue.add( "Shivansh" );
studentQueue.add( "Sohan" );
studentQueue.add( "Mohan" );
studentQueue.add( "Shivam" );
studentQueue.add( "Radha" );
studentQueue.add( "Rakesh" );
Iterator<String> studentQueueIterator = studentQueue.iterator();
while (studentQueueIterator.hasNext()) {
String name = studentQueueIterator.next();
System.out.println(name);
}
}
}
|
Output
Shivansh
Sohan
Mohan
Shivam
Radha
Rakesh
Share your thoughts in the comments
Please Login to comment...