Java - How to iterate over a PriorityQueue

Posted on October 27, 2016


See the below example, we can iterate a PriorityQueue by using 

  • For-each loop
  • Iterator
  • Stream (Introduced in Java8)

IterateQueueExample.java

/**
 * 
 */
package com.boraji.tutorial;

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


/**
 * @author imssbora
 *
 */
public class IterateQueueExample {
	public static void main(String[] args) {
		Queue<Integer> queue=new PriorityQueue<>();
		queue.add(1);
		queue.add(2);
		queue.add(3);
		queue.add(4);
		queue.add(5);
		
		/*Method 1 - Using for each loop*/
		System.out.println("Using for each loop");
		for (Integer element : queue) {
			System.out.println(element);
		}
		
		/*Method 2 - Using Iterator*/
		System.out.println("\nUsing Iterator");
		Iterator<Integer> iterator=queue.iterator();
		while(iterator.hasNext()){
			System.out.println(iterator.next());
		}
		
		/*Method 3 - Using Stream*/
		System.out.println("\nUsing Stream");
		queue.stream().forEach(e->System.out.println(e));
	}
}

Output

Using for each loop
1
2
3
4
5

Using Iterator
1
2
3
4
5

Using Stream
1
2
3
4
5