MAP遍历

/**
 * MAP遍历
 *
 * @author: NPF
 * @date: 2018/2/27.
 */
public class MapUtil {


public static void main(String[] args) {
    Map tempMap = new HashMap<>();
    tempMap.put("a", 111);
    tempMap.put("b", 222);
    tempMap.put("c", 333);

    each1(tempMap);
    each2(tempMap);
    each3(tempMap);
    each4(tempMap);
    eachMapList();


}

/**
 * JDK1.4
 * Map entrySet() 遍历
 *
 * @param tempMap
 */
private static void each1(Map tempMap) {
    Iterator it = tempMap.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        String key = (String) entry.getKey();
        Integer value = (Integer) entry.getValue();
        System.out.println("key=" + key + " value=" + value);
    }
}

/**
 * JDK1.5中,应用新特性For-Each循环
 *
 * @param tempMap
 */
private static void each2(Map tempMap) {
    for (Map.Entry entry : tempMap.entrySet()) {
        String key = entry.getKey();
        Integer value = entry.getValue();
        System.out.println("key=" + key + " value=" + value);
    }
}

/**
 * Map keySet() 遍历
 *
 * @param tempMap
 */
private static void each3(Map tempMap) {
    /**
     * 循环获取key,通过key再获取value
     */
    for (Iterator i = tempMap.keySet().iterator(); i.hasNext(); ) {
        String key = (String) i.next();
        Integer value = tempMap.get(key);
        System.out.println("key=" + key + " value=" + value);
    }
    /**
     * 循环获取value
     */
    for (Iterator i = tempMap.values().iterator(); i.hasNext(); ) {
        Integer value = (Integer) i.next();
        System.out.println("value=" + value);
    }
}

/**
 * Map keySet()遍历
 *
 * @param tempMap
 */
private static void each4(Map tempMap) {
    for (String key : tempMap.keySet()) {
        Integer value = tempMap.get(key);
        System.out.println("key=" + key + " value=" + value);
    }
}

/**
 * 遍历Map  map = new HashMap <>();
 */
private static void eachMapList() {
    /**
     * 方式一
     */
    Map> map1 = new HashMap<>();
    Set keys = map1.keySet();
    Iterator iterator = keys.iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        ArrayList arrayList = map1.get(key);
        for (String value : arrayList) {
            System.out.println(key + "==方式一==" + value);
        }
    }
    /**
     * 方式二
     */
    Map> map2 = new HashMap<>();
    for (Map.Entry entry : map2.entrySet()) {
        String key = entry.getKey().toString();
        List list = (List) entry.getValue();
        for (String value : list) {
            System.out.println(key + "==方式二==" + value);
        }
    }

}}

你可能感兴趣的:(MAP遍历)