温馨提示×

Map.Entry使用详解

小云
79
2023-09-28 06:28:47
栏目: 编程语言

Map.Entry是Map接口中的一个内部接口,它表示Map中的一个键值对。

Map.Entry接口有以下方法:

getKey():返回该键值对的键。

getValue():返回该键值对的值。

setValue(V value):设置该键值对的值。

通过Map的entrySet()方法可以获取一个包含所有键值对的Set集合,每个键值对都是一个Map.Entry类型的对象。

使用Map.Entry可以遍历Map集合中的所有键值对,例如:

Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Orange", 3);
// 遍历Map集合
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}

输出结果:

Key: Apple, Value: 1
Key: Banana, Value: 2
Key: Orange, Value: 3

这样我们就可以通过Map.Entry的getKey()方法获取键,通过getValue()方法获取值,实现对Map集合的遍历和操作。

0