创建HashMap集合

1
2
3
4
HashMap<Integer, String> hashMap = new HashMap<>(16);
hashMap.put(1, "a");
hashMap.put(2, "b");
hashMap.put(3, "c");

遍历

keySet()

使用keySet()方法,先遍历键,再取出值

1
2
3
for (Integer key : hashMap.keySet()) {
System.out.println("key=" + key + ",value=" + hashMap.get(key));
}

values()

使用values()方法,直接遍历值

1
2
3
for (String value : hashMap.values()) {
System.out.println(value);
}

entrySet()

使用entrySet()方法,然后通过getKey()和getValue()分别取键和值

1
2
3
for (Map.Entry entry : hashMap.entrySet()) {
System.out.println("key=" + entry.getKey() + ",value=" + entry.getValue());
}

ForEach()

通过ForEach()方法直接遍历

1
hashMap.forEach((key, value) -> System.out.println(key + "," + value));