温馨提示×

java怎么建立映射关系

小亿
98
2023-12-12 03:57:37
栏目: 编程语言

在Java中,可以使用Map接口的实现类来建立映射关系。常用的Map实现类有HashMapTreeMapLinkedHashMap

以下是建立映射关系的一些常见操作:

  1. 创建一个Map对象:
Map<String, Integer> map = new HashMap<>();
  1. 添加键值对到映射中:
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
  1. 从映射中获取值:
int value1 = map.get("key1"); // 返回1
  1. 检查映射中是否包含某个键:
boolean containsKey = map.containsKey("key1"); // 返回true
  1. 检查映射中是否包含某个值:
boolean containsValue = map.containsValue(1); // 返回true
  1. 遍历映射的键值对:
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey();
    Integer value = entry.getValue();
    System.out.println(key + " = " + value);
}
  1. 删除映射中的键值对:
map.remove("key1");

请注意,Map接口允许键和值为null,但HashMapTreeMap不支持null键,LinkedHashMap除外。

0