对Map集合的几种遍历

1、通过map.keySet()获取到map对象键的Set集合,再通过遍历该Set集合中的每一个key来获取对应的value

Map map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
map.put("key4", "value4");

for(String s: map.keySet()) {
	System.out.println("key:"+s+"   value:"+map.get(s));
}

2、只遍历map中的键或者值

Map map = new HashMap<>();
		map.put("key1", "value1");
		map.put("key2", "value2");
		map.put("key3", "value3");
		map.put("key4", "value4");
		//只遍历键
	for(String k:map.keySet()) {
		System.out.println("key:"+k);
	}
	//只遍历值
	for(String v:map.values()) {
		System.out.println("value:"+v);
	}

3、通过Map.Entry获取

		Map map = new HashMap<>();
		map.put("key1", "value1");
		map.put("key2", "value2");
		map.put("key3", "value3");
		map.put("key4", "value4");
		
	for(Map.Entry entry:map.entrySet()) {
	System.out.println("key:"+entry.getKey()+"value:"+entry.getValue());
		}
	}

4、
Iterator遍历获取,然后获取到Map.Entry,再得到getKey()和getValue()

Map map = new HashMap<>();
	map.put("key1", "value1");
	map.put("key2", "value2");
	map.put("key3", "value3");
	map.put("key4", "value4");
Iterator> it  =map.entrySet().iterator();
	while(it.hasNext()) {
		Map.Entry entry = it.next();
		System.out.println("key:"+entry.getKey()+"   value:"+entry.getValue());
		}
	}

你可能感兴趣的:(JavaSE学习笔记,Java,Map集合,遍历)