获取map集合中键和值的三种方式
时间:2019-05-20 22:51:46
收藏:0
阅读:210
//创建一个map集合
HashMap<String, Integer> map = new HashMap<>();
//添加元素
map.put("小王",25);
map.put("小张",35);
map.put("小李",20);
方法一:用增强for循环
//用keyset()方法获取所有的键
Set<String> keys = map.keySet();
for(String s:keys){
Integer value = map.get(s);
System.out.print(s+" ");
System.out.print(value+" ");
}
方法二:用迭代器
//用keyset()方法获取所有的键
Set<String> keys = map.keySet();
//获取迭代器
Iterator<String> it = keys.iterator();
while(it.hasNext()){
String key = it.next();
Integer value = map.get(key);
System.out.println(key+"******"+value);
}
方法三:使用EntrySet()方法
//用EntrySet()方法把成对儿的键值放入到Set集合中
Set<Map.Entry<String, Integer>> entry = map.entrySet();
//for循环遍历
for(Map.Entry s:entry){
String key = (String)s.getKey();
int value = (int)s.getValue();
System.out.println(key+"*****"+value);
}
原文:https://www.cnblogs.com/Hubert-dzl/p/10897007.html
评论(0)