HashMapkeySet()hashMap = new HashMap<>(16); hashMap.put(1, "a"); hashMap.put(2, "b"); hashMap.put(3, "c");
使用keySet()方法,先遍历键,再取出值
for (Integer key : hashMap.keySet()) {
System.out.println("key=" + key + ",value=" + hashMap.get(key));
}
values()
使用values()方法,直接遍历值
for (String value : hashMap.values()) {
System.out.println(value);
}
entrySet()
使用entrySet()方法,然后通过getKey()和getValue()分别取键和值
for (Map.Entry entry : hashMap.entrySet()) {
System.out.println("key=" + entry.getKey() + ",value=" + entry.getValue());
}
ForEach()
通过ForEach()方法直接遍历
hashMap.forEach((key, value) -> System.out.println(key + "," + value));



