Map遍历方法

我们经常用到Map集合,往往需要遍历它,下面记录几种遍历Map的方法:

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


public class MapTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
        //Map遍历方法1
        System.out.println("Map遍历方法1");
        Set<String> set = map.keySet();
        for (String string : set) {
            System.out.println(string + " = " + map.get(string));
        }
        //Map遍历方法2
        System.out.println("Map遍历方法2");
        Set<Entry<String, String>> entries = map.entrySet();
        for (Entry<String, String> entry : entries) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
        //Map遍历方法3
        System.out.println("Map遍历方法3");
        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String string = (String) iterator.next();
            System.out.println(string + " = " + map.get(string));
        }
        //Map遍历方法4
        System.out.println("Map遍历方法4");
        Iterator<String> iterator2 = map.values().iterator();
        while (iterator2.hasNext()) {
            String string = (String) iterator2.next();
            System.out.println(string);
        }
    }

}

 

posted @ 2013-05-29 15:04  百里抱木  阅读(193)  评论(0编辑  收藏  举报