A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 达达123 中级黑马   /  2016-11-10 19:44  /  926 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

思路:
获取所有键值对对象的集合
遍历键值对对象的集合,获取到每一个键值对对象
根据键值对对象找键和值

B:案例演示

Map集合的遍历之键值对对象找键和值
HashMap<String, Integer> hm = new HashMap<>();
hm.put("张三", 23);
hm.put("李四", 24);
hm.put("王五", 25);
hm.put("赵六", 26);
/*Set<Map.Entry<String, Integer>> entrySet = hm.entrySet(); //获取所有的键值对象的集合
Iterator<Entry<String, Integer>> it = entrySet.iterator();//获取迭代器
while(it.hasNext()) {
    Entry<String, Integer> en = it.next();              //获取键值对对象
    String key = en.getKey();                               //根据键值对对象获取键
    Integer value = en.getValue();                          //根据键值对对象获取值
    System.out.println(key + "=" + value);
}*/

for(Entry<String,Integer> en : hm.entrySet()) {
    System.out.println(en.getKey() + "=" + en.getValue());
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马