Map<String,String> map = new HashMap<>();
map.put("one","one_value");
map.put("two","two_value");
map.put("three","three_value");
map.put("four","four_value");
map.put("five","five_value");
map.put("six","six_value");
//方式1 entrySet得到key和value
for(Map.Entry<String,String> entry:map.entrySet()) {
System.out.println("key="+entry.getKey()+","+"value="+entry.getValue());
}
//方式2 keySet得到key
for(String keys:map.keySet()){
System.out.println("key="+keys);
}
//方式3 values得到value
for(String val:map.values()){
System.out.println("value="+val);
}
//方式4 Iterator
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()+","+"value="+entry.getValue());
}
//方式4 forEach
map.forEach((key,value)->{
System.out.println("key="+key+","+"value="+value);
});
Map的遍历方式
最新推荐文章于 2024-07-01 16:13:53 发布