Java HashMap

本文最后更新于 2024年10月13日 晚上

HashMap

作用

字典

方法

创建

1
HashMap<Integer, Integer> hm = new HashMap<>();

添加键值对

1
2
3
4
5
6
hm.put(1,2);
hm.putIfAbsent(2,3); //仅在hm原本不包含2对应的键值对时执行添加2-3键值对的操作

// 添加所有键值对
HashMap<Integer, Integer> hm2 = new HashMap<>();
hm2.putAll(hm);

删除键值对

1
hm.remove(1);

访问键值对

1
System.out.println(hm.get(2)); // 打印2对应的元素

迭代

1
2
3
4
5
6
7
8
9
10
11
// 对键集合遍历for循环
for (Integer i : hm.keySet()) {
System.out.println("key: " + i + " values: " + Sites.get(i));
}

// iterator
Iterator<Integer> it = hm.keySet().iterator();
while (it.hasNext()) {
int key = it.next;
System.out.println("key: " + key + " values: " + Sites.get(key));
}

merge

1
hashmap.merge(key, value, remappingFunction)

如果 key 对应的 value 不存在,则返回该 value 值,如果存在,则返回通过 remappingFunction 重新计算后的值。

1
hm2.merge(1,1,(k,v)->v+1); // 若keySet中不包含1,则插入1-1键值对,若有则对v加一

compute

1
hashmap.compute(K key, BiFunction remappingFunction);

hashMap中的指定key的值进行重新计算

key对应的value不存在,则返回null,若存在则返回通过remappingFunction重新计算后的值

1
int newPrice = prices.compute("Shoes", (key, value) -> value - value * 10/100);

Java HashMap
https://meteor041.git.io/2024/10/12/Java-HashMap/
作者
meteor041
发布于
2024年10月12日
许可协议