What are the ways to iterate through a hashmap?
There are several ways to iterate through a HashMap.
- set of entries
HashMap<String, Integer> map = new HashMap<>();
// 添加键值对
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
// 处理键值对
}
- Return a set of all keys in the map.
HashMap<String, Integer> map = new HashMap<>();
// 添加键值对
for (String key : map.keySet()) {
Integer value = map.get(key);
// 处理键值对
}
- Return a list of all the values in the given dictionary.
HashMap<String, Integer> map = new HashMap<>();
// 添加键值对
for (Integer value : map.values()) {
// 处理值
}
- You can use the forEach method in Java 8 to iterate through the key-value pairs in a HashMap.
HashMap<String, Integer> map = new HashMap<>();
// 添加键值对
map.forEach((key, value) -> {
// 处理键值对
});