5 Ways to Traverse HashMap in Java
There are several ways to iterate through a HashMap.
- Traverse using Iterator: By obtaining the iterator of the HashMap, iterate through the entire HashMap using a while loop and the next() method of the Iterator.
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加元素到HashMap...
Iterator<Map.Entry<String, Integer>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
// 处理每个键值对
}
- To iterate using a For-Each loop: directly obtain the key-value pairs collection by using the entrySet() method of the HashMap, and then iterate through it using a For-Each loop.
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加元素到HashMap...
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
// 处理每个键值对
}
- Using Lambda expressions in Java 8 to traverse: By using the forEach() method of HashMap in conjunction with Lambda expressions, you can traverse HashMap more succinctly.
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加元素到HashMap...
hashMap.forEach((key, value) -> {
// 处理每个键值对
});
It is important to note that the traversal order of a HashMap is not fixed, as a HashMap does not guarantee the order of stored elements. If a specific order is needed for traversing a HashMap, consider using classes such as LinkedHashMap that maintain the order of insertion or access.