Map.Entry
-
getKey(): 返回与此项对应的键。
-
getValue(): 返回与此项对应的值。
-
setValue(V value): 用指定的值替换与此项对应的值。
Map.Entry
通常用于迭代 Map
中的键值对,尤其是在使用迭代器遍历 Map
的情况下。通过 Map
的 entrySet()
方法可以获取包含所有键值对的集合,每个元素都是 Map.Entry
。
import java.util.HashMap;
import java.util.Map;
public class MapEntryExample {
public static void main(String[] args) {
// 创建一个HashMap
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
// 使用entrySet()获取键值对集合
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
}
}