Map遍历的几种方法

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

public class MapUtil {

    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<String,Integer>();
        map.put("age", 12);
        map.put("sg", 163);
        map.put(null, null);
        bl1(map);
        bl2(map);
        bl3(map);
        bl4(map);
    }



    /**
     * 输出 key value 常用的方法,尤其是容量大时,速度相对快
     * @param map
     */
    private static void bl3(Map<String, Integer> map) {
        Iterator<Entry<String, Integer>> iterator = map.entrySet().iterator();
        while(iterator.hasNext()) {
            Entry<String, Integer> next = iterator.next();
            System.out.println("f3=="+next.getKey());
            System.out.println("f3=="+next.getValue());
        }
    }

    /**
     * 输出 key value 速度也可以
     * @param map
     */
    private static void bl1(Map<String, Integer> map) {
        for(Entry<String, Integer> entry: map.entrySet()) {
            System.out.println("f1=="+entry.getKey());
            System.out.println("f1=="+entry.getValue());
        }
    }
    
    /**
     * 只输出value
     * @param map
     */
    private static void bl4(Map<String, Integer> map) {
        for(Integer value:map.values()) {
            System.out.println("f4=="+value);
        }
    }

    /**
     * 只输出key
     * @param map
     */
    private static void bl2(Map<String, Integer> map) {
        for(String key:map.keySet()) {
            System.out.println("f2=="+key);
        }
    }

}

 

posted @ 2018-12-31 17:00  xxBai  阅读(280)  评论(0编辑  收藏  举报