import java.util.HashMap;
import java.util.Map;
public class MapIterationExample {
public static void main(String[] args) {
// 创建一个HashMap实例
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Orange", 3);
// 方法1: 使用for-each循环遍历键集
System.out.println("Method 1: Iterate over keys using for-each loop");
for (String key : map.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
// 方法2: 使用for-each循环遍历entrySet
System.out.println("\nMethod 2: Iterate over entries using for-each loop");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
// 方法3: 使用Iterator遍历entrySet
System.out.println("\nMethod 3: Iterate over entries using Iterator");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
// 方法4: 使用Java 8的forEach方法
System.out.println("\nMethod 4: Iterate using Java 8 forEach method");
map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
}
}
HashMap实例,并向其中添加了一些键值对。for-each循环遍历键集(keySet),然后通过键获取对应的值。for-each循环遍历entrySet,直接访问键和值。这是最常用的方法之一,因为它效率较高且代码简洁。Iterator遍历entrySet,这种方式在需要手动控制迭代时很有用。forEach方法,它提供了一种更简洁的方式来进行遍历操作。以上是几种常见的遍历Map的方式。
上一篇:java charset
下一篇:java枚举用法示例
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站