黑马程序员技术交流社区

标题: Map集合中如何获取键和值 [打印本页]

作者: 达达123    时间: 2016-11-10 19:44
标题: Map集合中如何获取键和值
思路:
获取所有键值对对象的集合
遍历键值对对象的集合,获取到每一个键值对对象
根据键值对对象找键和值

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());
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2