Map<String, Object> map=new HashMap<String, Object>();
map.put("one", "one");
map.put("two", "two");
map.put("three", "three");
// (1)map的遍历种类 map.keySet()获取map中所有的key值 通过map.get(key)获取value值
for(String index:map.keySet()){
System.out.println(map.get(index));
}
// (2) 直接遍历map的values值
for(Object str:map.values()){
System.out.println(str.toString());
}
// (3) map.entrySet().iterator() 使用迭代器进行map数据的遍历 ,hasNext() 判断有没有下一个数据 有则返回true 没有就返回false
Iterator<Entry<String, Object>> it = map.entrySet().iterator();
while(it.hasNext()){
Entry<String, Object> entry = it.next();
System.out.println(entry.getKey()+":"+entry.getValue());
}
// (4)运用增强for循环来进行对map数据的遍历,对键和值都有遍历。
for (Entry<String, Object>entry1 : map.entrySet()) {
System.out.println(entry1.getKey()+":"+entry1.getValue());
}
浅谈map的遍历方式
最新推荐文章于 2022-05-11 13:54:27 发布