1. 使用 entrySet
遍历
entrySet
返回包含映射中所有键值对的集合,可以通过增强 for
循环遍历这个集合。
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
2. 使用 keySet
遍历
keySet
返回所有键的集合,可以通过增强 for
循环遍历键,然后通过键获取对应的值。
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
for (String key : map.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
}
}
3. 使用 values
遍历
values
返回所有值的集合,可以直接遍历这个集合(通常用于仅需要值的情况)。
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
for (Integer value : map.values()) {
System.out.println("Value: " + value);
}
}
}
4. 使用 Iterator
遍历
可以使用迭代器遍历 entrySet
,这种方式提供了在遍历过程中删除元素的能力。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
// 如果需要删除元素,可以使用 iterator.remove() 方法
}
}
}
5. 使用 forEach
方法(Java 8 及以上)
Java 8 引入了 forEach
方法,可以通过 lambda 表达式遍历 HashMap
。
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
map.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value: " + value);
});
}
}
6、总结
以上展示了五种遍历 HashMap
的方法,每种方法都有其适用的场景:
entrySet
:同时需要键和值的情况。keySet
:只需要键或需要键后获取值的情况。values
:只需要值的情况。Iterator
:需要在遍历过程中删除元素的情况。forEach
:使用 Java 8 及以上版本的简洁遍历方式。