一.前言
HashMap无论是在工作中还是在面试中都非常常用,下面介绍一下遍历一个HashMap的四种方式
二.代码
1.通过keySet来遍历所有的value
Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
System.out.println("key= "+ key + " and value= " + map.get(key));
}
此种方法不建议使用:效率低,因为实际上先使用了迭代器,又从map中调用get,遍历了两次
2.使用iterator遍历key和value
Map<String, String> map = new HashMap<String, String>();
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
3.通过Map.entrySet遍历key和value
Map<String, String> map = new HashMap<String, String>();
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
4.通过Map.values()遍历所有的value
Map<String, String> map = new HashMap<String, String>();
for(String v:map.values())
{
System.out.println("The value is "+v);
}
5.Java8新增的ForEach()方法
//Java8新增了stream 可进行函数式编程
map.forEach((key,value)->{
System.out.println("key="+key,"value="+value);
})