// Java Map for循环示例代码
import java.util.HashMap;
import java.util.Map;
public class MapForLoopExample {
public static void main(String[] args) {
// 创建一个HashMap实例
Map<String, Integer> map = new HashMap<>();
// 向Map中添加键值对
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
// 使用for-each循环遍历Map的键集
for (String key : map.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
// 使用entrySet()方法遍历Map的键值对
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
HashMap
来创建一个Map
对象,并向其中添加一些键值对。map.keySet()
获取所有键的集合,然后使用for-each循环遍历这些键,并通过map.get(key)
获取对应的值。map.entrySet()
获取所有键值对的集合,然后使用for-each循环遍历每个Entry
对象,直接访问键和值。这种方式效率更高,因为它不需要在每次迭代时调用get
方法。希望这段代码和解释对你有帮助!
下一篇:java迭代器iterator
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站