1.Queue遍历
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
public class QunueBianli {
public static void main(String[] args){
Queue<Integer> q = new LinkedBlockingQueue<Integer>();
//初始化队列
for (int i = 0;i<5;i++){
//添加元素 offer
((LinkedBlockingQueue<Integer>) q).offer(i);
}
System.out.println("---------1---------");
//集合式遍历,元素不会被移除
for (Integer x:q){
System.out.print(x);
}
System.out.println("\n---------2---------");
//队列式遍历,元素逐个被移除
while (q.peek() != null){
//poll返回第一个元素,并在队列中删除
System.out.print(q.poll());
}
}
}
2.Stack遍历
import java.util.Stack;
public class StackBianli {
public static void main(String[] args){
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0;i<10;i++){
//向栈中添加元素,返回结果是当前添加的元素
stack.push(i);
}
//集合式遍历
System.out.println("---------1---------");
for (Integer x:stack){
System.out.print(x);
}
System.out.println("\n---------2---------");
//栈弹出遍历方式
//while(s.peek() != null) 不健壮的判断方式容易异常,正确写法是下面的
while (!stack.empty()){
System.out.print(stack.pop());
}
}
}
3.map遍历
import java.util.HashMap;
import java.util.Map;
public class mapBianli {
public static void main(String[] args){
Map<String,String> map = new HashMap<String, String>();
map.put("1","a");
map.put("2","b");
map.put("3","c");
//最简洁,最通用的遍历方式
for (Map.Entry<String,String> entry : map.entrySet()){
System.out.println("key: " + entry.getKey() + "value: " + entry.getValue());
}
//lambda表达式
System.out.println("lambda表达式方法:");
map.forEach((k,v) -> System.out.println("k:"+k+"v:"+v));
}
}