Java - How to iterate a Deque

Posted on October 27, 2016


We can iterate a Deque in java using 

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

See the below example.

IterateDequeExample.java

package com.boraji.tutorial;

import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;

/**
 * @author imssbora
 *
 */
public class IterateDequeExample {
	public static void main(String[] args) {
		Deque<String> deque=new LinkedList<>();
		deque.add("A");
		deque.add("B");
		deque.add("C");
		deque.add("D");
		deque.add("E");
		deque.add("F");
		
		/*Method 1 - Using for-each loop*/
		System.out.println("Using for-each loop");
		for (String element : deque) {
			System.out.println(element);
		}
		
		/*Method 2 - Using Iterator*/
		System.out.println("\nUsing Iterator");
		for (Iterator<String> iterator = deque.iterator(); iterator.hasNext();) {
			String element = iterator.next();
			System.out.println(element);
		}
		
		/*Method 3 - Using Stream*/
		System.out.println("\nUsing Stream");
		deque.stream().forEach(e->System.out.println(e));
	}
}

Output

Using for-each loop
A
B
C
D
E
F

Using Iterator
A
B
C
D
E
F

Using Stream
A
B
C
D
E
F