1. 程式人生 > >Java集合的Stack、Queue、Map的遍歷

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

import java.util.HashMap; 
import java.util.Iterator; 
import java.util.Map; 

/** 
* Map的遍歷,這個遍歷比較特殊,有技巧 

* @author leizhimin 2009-7-22 15:15:34 
*/
 
public class TestMap { 
        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(entry.getKey() + " = " + entry.getValue()); 
                } 
                //Java5之前的比較簡潔的便利方式1 

                System.out.println("----1----"); 
                for (Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); it.hasNext();) { 
                        Map.Entry<String, String> entry = it.next(); 
                        System.out.println(entry.getKey() + " = "
 + entry.getValue()); 
                } 
                //Java5之前的比較簡潔的便利方式2 
                System.out.println("----2----"); 
                for (Iterator<String> it = map.keySet().iterator(); it.hasNext();) { 
                        String key = it.next(); 
                        System.out.println(key + " = " + map.get(key)); 
                } 
        } 
}