学习目标:
遍历Map的几种方式
学习内容:
Map<String,String> map = new HashMap<>();
for (int i = 0; i < 6; i++) {
map.put("slot"+i, i*4+"-"+(i+1)*4);
}
System.out.println(map.toString());
//第一种:普遍使用,二次取值 取keys或values 时,效率最高
System.out.println("通过Map.keySet遍历key和value:");
for (String key : map.keySet()) {
System.out.println("key= "+ key + " and value= " + map.get(key));
}
//第二种 迭代器
System.out.println("通过Map.entrySet使用iterator遍历key和value:");
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());
}
//第三种:最常用,推荐,尤其是容量大时
System.out.println("通过Map.entrySet遍历key和value");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第四种
System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
for (String v : map.values()) {
System.out.println("value= " + v);
}
System.out.println("======== java 8支持: forEach 效率最低 ==========");
map.forEach( (key,value) -> {System.out.println("Key = " + key+ ", Value = "+ value);} );
System.out.println("======== java 8支持: stream ForEach 流式 ==========");
map.entrySet().stream().forEach( (entry) -> System.out.println("Key = " + entry.getKey()+ ", Value = "+ entry.getValue()));
map.entrySet().stream().forEach( System.out::println);
遍历结果:
{slot5=20-24, slot4=16-20, slot3=12-16, slot2=8-12, slot1=4-8, slot0=0-4}
通过Map.keySet遍历key和value:
key= slot5 and value= 20-24
key= slot4 and value= 16-20
key= slot3 and value= 12-16
key= slot2 and value= 8-12
key= slot1 and value= 4-8
key= slot0 and value= 0-4
通过Map.entrySet使用iterator遍历key和value:
key= slot5 and value= 20-24
key= slot4 and value= 16-20
key= slot3 and value= 12-16
key= slot2 and value= 8-12
key= slot1 and value= 4-8
key= slot0 and value= 0-4
通过Map.entrySet遍历key和value
key= slot5 and value= 20-24
key= slot4 and value= 16-20
key= slot3 and value= 12-16
key= slot2 and value= 8-12
key= slot1 and value= 4-8
key= slot0 and value= 0-4
通过Map.values()遍历所有的value,但不能遍历key
value= 20-24
value= 16-20
value= 12-16
value= 8-12
value= 4-8
value= 0-4
======== java 8支持: forEach 效率最低 ==========
Key = slot5, Value = 20-24
Key = slot4, Value = 16-20
Key = slot3, Value = 12-16
Key = slot2, Value = 8-12
Key = slot1, Value = 4-8
Key = slot0, Value = 0-4
======== java 8支持: stream ForEach 流式 ==========
Key = slot5, Value = 20-24
Key = slot4, Value = 16-20
Key = slot3, Value = 12-16
Key = slot2, Value = 8-12
Key = slot1, Value = 4-8
Key = slot0, Value = 0-4
slot5=20-24
slot4=16-20
slot3=12-16
slot2=8-12
slot1=4-8
slot0=0-4
总结:
values()是返回Map的所有value的集合collection,只能遍历到值,很难遍历到key所以一般不用,除非在某种特殊场合。
测试表明entrySet()方式遍历效率更高。
学习时间:
2021-08-23
总结
附: