问题:
用代码写出遍历map的方式。
代码:
import java.util.HashMap;
import java.util.Map;
//4.用代码写出遍历map的方式。
public class TM04 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 5);
map.put("banana", 7);
map.put("orange", 3);
// 1. 使用entrySet()方法遍历Map
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
// 2. 使用keySet()方法遍历Map
for (String key : map.keySet()) {
Integer value = map.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
// 3. 使用values()方法遍历Map
for (Integer value : map.values()) {
System.out.println("Value: " + value);
}
// 4. 使用Lambda表达式遍历Map(Java 8及以上版本)
map.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value: " + value);
});
}
}