java中Map的5种遍历方式
直接上代码
/**
* Map集合的遍历方式:5种
*/
public void forToMap(){
HashMap<String, String> map = new HashMap<>();
map.put("1", "One");
map.put("2", "Two");
map.put("3", "Three");
//1.通过map对象的entrySet遍历Map
for (Map.Entry<String, String> entry:map.entrySet()){
System.out.println("key="+entry.getKey()+",value="+entry.getValue());
}
//2.通过迭代器(Iterator)的方式遍历Map
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String, String> next = iterator.next();
System.out.println("key="+next.getKey()+",value="+next.getValue());
}
//3.通过map对象的keySet()遍历Map
for (String key:map.keySet()){
System.out.println("key="+key+",value="+map.get(key));
}
//4.通过map对象的values()遍历Map(只能遍历到Map的所有value,但是无法获取Map的key)
for(String value:map.values()){
System.out.println("value="+value);
}
//5.通过Lambda表达式的方式遍历Map
map.forEach((key,value)->{
System.out.println("key="+key+",value="+value);
});
//或
map.forEach((key,value)-> System.out.println("key="+key+",value="+value) );
//只有一行代码可以省略大括号{}
}
参考:
https://blog.csdn.net/m0_67401606/article/details/123642569