在java中,可以使用以下方式来迭代一个Deque:
- For-each循环
- 迭代器(Iterator)
- Stream(在Java8中引入)
请参阅以下示例。文件:IterateDequeExample.java
package com.yiibai.tutorial;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
/**
* @author yiibai
*
*/
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));
}
}
执行上面示例代码,得到以下结果:
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