Map学习一之基本遍历元素的方法二entrySet

24次阅读

共计 1102 个字符,预计需要花费 3 分钟才能阅读完成。

package com.itheima.demo01.Map;

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

/*

Map 集合遍历的第二种方式: 使用 Entry 对象遍历

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

*/
public class Demo03EntrySet {

public static void main(String[] args) {
    // 创建 Map 集合对象
    Map<String,Integer> map = new HashMap<>();
    map.put("赵丽颖",168);
    map.put("杨颖",165);
    map.put("林志玲",178);

    //1. 使用 Map 集合中的方法 entrySet(), 把 Map 集合中多个 Entry 对象取出来, 存储到一个 Set 集合中
    Set<Map.Entry<String, Integer>> set = map.entrySet();

    //2. 遍历 Set 集合, 获取每一个 Entry 对象
    // 使用迭代器遍历 Set 集合
    Iterator<Map.Entry<String, Integer>> it = set.iterator();
    while(it.hasNext()){Map.Entry<String, Integer> entry = it.next();
        //3. 使用 Entry 对象中的方法 getKey() 和 getValue() 获取键与值
        String key = entry.getKey();
        Integer value = entry.getValue();
        System.out.println(key+"="+value);
    }
    System.out.println("-----------------------");
    for(Map.Entry<String,Integer> entry:set){//3. 使用 Entry 对象中的方法 getKey() 和 getValue() 获取键与值
        String key = entry.getKey();
        Integer value = entry.getValue();
        System.out.println(key+"="+value);
    }
}

}

正文完
 0