本文目录导读:

- 使用 entrySet() 遍历(推荐,效率最高)
- 使用 keySet() 遍历
- 使用 values() 遍历(只遍历值)
- 使用 Lambda 表达式(Java 8+)
- 使用 Stream API(Java 8+)
- 完整实例:Map遍历的实用场景
- 性能对比和选择建议
- 选择建议
- 注意事项
在Java中遍历Map有多种方式,我来为你详细讲解各种遍历方法及案例。
使用 entrySet() 遍历(推荐,效率最高)
增强for循环 + entrySet()
import java.util.HashMap;
import java.util.Map;
public class MapTraversalExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Java", 100);
map.put("Python", 95);
map.put("JavaScript", 90);
map.put("Go", 85);
// 方式1:增强for循环遍历entrySet
System.out.println("=== 方式1: entrySet + 增强for ===");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
Iterator + entrySet()
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MapTraversalExample2 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Java", 100);
map.put("Python", 95);
map.put("JavaScript", 90);
// 方式2:Iterator遍历entrySet
System.out.println("=== 方式2: Iterator + entrySet ===");
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());
}
}
}
使用 keySet() 遍历
keySet + 增强for(只遍历key,然后通过key获取value)
import java.util.HashMap;
import java.util.Map;
public class MapTraversalExample3 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Java", 100);
map.put("Python", 95);
map.put("JavaScript", 90);
// 方式3:遍历keySet
System.out.println("=== 方式3: keySet + 增强for ===");
for (String key : map.keySet()) {
Integer value = map.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
使用 values() 遍历(只遍历值)
只遍历value
import java.util.HashMap;
import java.util.Map;
public class MapTraversalExample4 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Java", 100);
map.put("Python", 95);
map.put("JavaScript", 90);
// 方式4:遍历values(只能获取值)
System.out.println("=== 方式4: values() ===");
for (Integer value : map.values()) {
System.out.println("Value: " + value);
}
}
}
使用 Lambda 表达式(Java 8+)
forEach + Lambda
import java.util.HashMap;
import java.util.Map;
public class MapTraversalExample5 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Java", 100);
map.put("Python", 95);
map.put("JavaScript", 90);
// 方式5:Lambda表达式
System.out.println("=== 方式5: Lambda表达式 ===");
map.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value: " + value);
});
}
}
使用 Stream API(Java 8+)
Stream流遍历
import java.util.HashMap;
import java.util.Map;
public class MapTraversalExample6 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Java", 100);
map.put("Python", 95);
map.put("JavaScript", 90);
map.put("Go", 85);
// 方式6:Stream API遍历
System.out.println("=== 方式6: Stream API ===");
map.entrySet().stream()
.filter(entry -> entry.getValue() > 90) // 过滤条件
.forEach(entry -> {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
});
}
}
完整实例:Map遍历的实用场景
import java.util.HashMap;
import java.util.Map;
public class MapTraversalCompleteExample {
public static void main(String[] args) {
// 创建学生成绩表
Map<String, Double> studentScores = new HashMap<>();
studentScores.put("张三", 95.5);
studentScores.put("李四", 88.0);
studentScores.put("王五", 92.5);
studentScores.put("赵六", 78.5);
studentScores.put("孙七", 89.0);
// 场景1:打印所有学生成绩
System.out.println("===== 所有学生成绩 =====");
studentScores.forEach((name, score) -> {
System.out.printf("学生: %s, 成绩: %.1f%n", name, score);
});
// 场景2:计算平均分
System.out.println("\n===== 计算平均分 =====");
double total = 0;
int count = 0;
for (Double score : studentScores.values()) {
total += score;
count++;
}
double average = total / count;
System.out.printf("平均分: %.2f%n", average);
// 场景3:找出最高分和最低分的学生
System.out.println("\n===== 最高分和最低分 =====");
Map.Entry<String, Double> maxEntry = null;
Map.Entry<String, Double> minEntry = null;
for (Map.Entry<String, Double> entry : studentScores.entrySet()) {
if (maxEntry == null || entry.getValue() > maxEntry.getValue()) {
maxEntry = entry;
}
if (minEntry == null || entry.getValue() < minEntry.getValue()) {
minEntry = entry;
}
}
System.out.printf("最高分: %s (%.1f分)%n", maxEntry.getKey(), maxEntry.getValue());
System.out.printf("最低分: %s (%.1f分)%n", minEntry.getKey(), minEntry.getValue());
// 场景4:分类统计(使用Stream API)
System.out.println("\n===== 成绩分类 =====");
studentScores.forEach((name, score) -> {
String level;
if (score >= 90) {
level = "优秀";
} else if (score >= 80) {
level = "良好";
} else if (score >= 70) {
level = "中等";
} else {
level = "及格";
}
System.out.printf("%s: %s%n", name, level);
});
// 场景5:在遍历时删除元素(使用Iterator)
System.out.println("\n===== 删除不及格学生 =====");
studentScores.entrySet().removeIf(entry -> entry.getValue() < 60);
System.out.println("删除后的成绩表:");
studentScores.forEach((name, score) ->
System.out.printf("%s: %.1f%n", name, score));
}
}
性能对比和选择建议
public class MapTraversalPerformance {
public static void main(String[] args) {
// 创建大量数据测试性能
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < 100000; i++) {
map.put(i, i * 10);
}
long startTime, endTime;
// 1. entrySet遍历
startTime = System.nanoTime();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int key = entry.getKey();
int value = entry.getValue();
}
endTime = System.nanoTime();
System.out.println("entrySet遍历: " + (endTime - startTime) / 1000000 + " ms");
// 2. keySet遍历(需要get操作,性能较差)
startTime = System.nanoTime();
for (Integer key : map.keySet()) {
int value = map.get(key);
}
endTime = System.nanoTime();
System.out.println("keySet遍历: " + (endTime - startTime) / 1000000 + " ms");
// 3. Lambda遍历
startTime = System.nanoTime();
map.forEach((key, value) -> {
// 处理逻辑
});
endTime = System.nanoTime();
System.out.println("Lambda遍历: " + (endTime - startTime) / 1000000 + " ms");
}
}
选择建议
- 需要同时获取key和value:使用
entrySet()或forEach()(Lambda) - 只需要key:使用
keySet() - 只需要value:使用
values() - 需要在遍历时删除元素:使用
Iterator或removeIf() - 需要复杂的变换操作:使用
Stream API - 追求最高性能:使用
entrySet()+ 增强for循环
注意事项
- 不要在使用
keySet()后通过get()获取value,因为这会降低性能 - 在遍历时不要直接修改Map的结构(增删元素),除非使用
Iterator的安全删除方法 - 选择合适的方法,不要为了展示技术而使用复杂的方法
- 如果只是遍历一次,
forEach()是最简洁的方法
掌握这些遍历方法,你就能根据不同的需求场景选择最合适的遍历方式了。