import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Queue;
import java.util.Stack;
import java.util.concurrent.LinkedBlockingQueue;
public class UtilTraversal {
public void mapTraversal(Map<String,Integer> map){
System.out.println("method one with java5's for");
for(Map.Entry<String,Integer> entry : map.entrySet()){
System.out.println(entry.getKey() +"="+ entry.getValue());
}
System.out.println("method two: with map.entrySet");
for(Iterator<Map.Entry<String,Integer>> it = map.entrySet().iterator(); it.hasNext();){
Map.Entry<String, Integer> entry = it.next();
System.out.println(entry.getKey()+"="+ entry.getValue());
}
System.out.println("method three with map.keySet");
for(Iterator<String> it = map.keySet().iterator(); it.hasNext();){
String key = it.next();
System.out.println(key +"=" + map.get(key));
}
}
public void stackTraversal(Stack<Integer> stack){
System.out.println("method one : 集合遍历方式 ");
for(Integer x : stack){
System.out.println(x);
}
System.out.println("method two ");
while(!stack.empty()){
System.out.println(stack.pop());
}
}
public void queueTraversal(Queue<Integer> queue){
System.out.println("method one : 集合遍历方式 ");
for(Integer x : queue){
System.out.println(x);
}
System.out.println("method two ");
while(queue.peek()!=null){
System.out.println(queue.poll());
}
}
public static void main(String[] args){
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
map.put("four", 4);
map.put("five", 5);
map.put("six", 6);
UtilTraversal ut = new UtilTraversal();
ut.mapTraversal(map);
System.out.println("++++++++++++++++++++++++++++++++++++++++++++");
Stack<Integer> stack = new Stack<Integer>();
for(int i=0;i<10;i++){
stack.push(i);
}
ut.stackTraversal(stack);
System.out.println("++++++++++++++++++++++++++++++++++++++++++++");
Queue<Integer> queue = new LinkedBlockingQueue<Integer>();
for(int i=0;i<10;i++){
queue.offer(i);
}
ut.queueTraversal(queue);
}
}
Java集合的Stack、Queue、Map的遍历
最新推荐文章于 2024-06-15 08:00:00 发布