62、Map集合的遍历方法二:使用entrySet()方法

遍历map的第二种方法:使用Entry遍历
一、Map集合中的方法:
        Set> entrySet() 返回此映射中包含的映射关系的set视图。
二、实现步骤:
    1、使用map结合用的方法entrySet(),把Map集合中多个Entry对象取出来,存储在一个Set集合中。
    2、遍历Set集合,获取每一个Entry对象。
    3、使用Entry对象的方法getKey()和getValue获取键和值。

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

public class ManEntry03 {
    public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("古力娜扎",168);
        map.put("赵丽颖",165);
        map.put("迪丽热巴",170);
        map.put("杨怡",162);
        map.put("谢娜",160);
        Set set = map.keySet();

        Set> en = map.entrySet();

        //使用迭代方式遍历
        Iterator> it = en.iterator();
        while(it.hasNext())
        {
            Map.Entry next = it.next();
            String key = next.getKey();
            Integer value = next.getValue();
            System.out.println(key + "=" + value);
        }
        System.out.println("=================================");
        //增强for循环
        for (Map.Entry sE : en) {
            Integer value = sE.getValue();
            String key = sE.getKey();
            System.out.println(key + "=" + value);
        }
    }
}

输出:

赵丽颖=165
迪丽热巴=170
杨怡=162
古力娜扎=168
谢娜=160
=================================
赵丽颖=165
迪丽热巴=170
杨怡=162
古力娜扎=168
谢娜=160

 

你可能感兴趣的:(01_JAVA)