在 Java 中,可以使用不同的方式来遍历 Map
的键值对。常见的方法包括使用 for-each
循环、forEach
方法以及 Iterator
。这里是一些常用的方式:
1. 使用 for-each
循环
import java.util.Map;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("a", "apple");
map.put("b", "banana");
map.put("c", "cherry");
// 使用 for-each 遍历 Map
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
2. 使用 forEach
方法(Java 8 及以上)
import java.util.Map;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("a", "apple");
map.put("b", "banana");
map.put("c", "cherry");
// 使用 forEach 方法遍历 Map
map.forEach((key, value) -> {
System.out.println(key + ": " + value);
});
}
}
3. 使用 Iterator
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("a", "apple");
map.put("b", "banana");
map.put("c", "cherry");
// 使用 Iterator 遍历 Map
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
这三种方法都能有效地遍历 Map
中的键值对,具体使用哪种方式可以根据自己的需求和代码风格来决定。
发表回复