Java集合的Stack、Queue、Map的遍历

  • importjava.util.HashMap;
  • importjava.util.Iterator;
  • importjava.util.Map;
  • importjava.util.Queue;
  • importjava.util.Stack;
  • importjava.util.concurrent.LinkedBlockingQueue;
  • publicclassUtilTraversal {
  •    publicvoidmapTraversal(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));
  •         }
  •     }
  •    publicvoidstackTraversal(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());
  •         }
  •     }
  •    publicvoidqueueTraversal(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());
  •         }
  •     }
  •    publicstaticvoidmain(String[] args){
  •         Map<String,Integer> map =newHashMap<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 =newUtilTraversal();
  •         ut.mapTraversal(map);
  •         System.out.println("++++++++++++++++++++++++++++++++++++++++++++");
  •         Stack<Integer> stack =newStack<Integer>();
  •         for(inti=0;i<10;i++){
  •             stack.push(i);
  •         }
  •         ut.stackTraversal(stack);
  •         System.out.println("++++++++++++++++++++++++++++++++++++++++++++");
  •         Queue<Integer> queue =newLinkedBlockingQueue<Integer>();
  •         for(inti=0;i<10;i++){
  •             queue.offer(i);
  •         }
  •         ut.queueTraversal(queue);
  •     }
  • }

评论

暂无评论