HashMap的四种遍历方式
package com.learning.java;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapTest {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("k1", 1);
map.put("k2", 2);
map.put("k3", 3);
//遍历方式1:利用Map.Entry
for (Map.Entry<String, Integer> m : map.entrySet()) {
String k = m.getKey();
int v = m.getValue();
System.out.println("key = " + k + ",value = " + v);
}
System.out.println("---------------------------");
//遍历方式2 利用iterator
Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Integer> next = it.next();
String k = next.getKey();
int v = next.getValue();
System.out.println("key = " + k + ",value = " + v);
}
System.out.println("---------------------------");
//遍历方式3 利用map.keySet 通过k获取v
for (String k : map.keySet()) {
int v = map.get(k);
System.out.println("key = " + k + ",value = " + v);
}
System.out.println("---------------------------");
//遍历方式4 jdk1.8特有
map.forEach((k, v) -> {
System.out.println("key = " + k + ",value = " + v);
});
}
}