Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

hashMap常用方法

清空hashMap

1
map.clear();

输出Key

1
2
3
4
5
// 输出 key 和 value
for (Integer i : Sites.keySet()) {
System.out.println("key: " + i + " value: " + Sites.get(i));
}

输出value

1
2
3
4
5
// 返回所有 value 值
for(String value: Sites.values()) {
// 输出每一个value
System.out.print(value + ", ");
}

输出key、value

1
2
3
4
for(Map.Entry<Integer,Integer> entry:map.entrySet()){
sout(entry.getkey())
sout(entry.getValue())
}

Integer i=map.putIfAbsent(“apple”,3)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//如果是第一次put,则返回值是null,且put进去。
//如果是第二次put这个key,则put不进去,返回这个key的value
```
HashMap<String, Integer> map = new HashMap<>();

// 第一次添加 - key 不存在
Integer result1 = map.putIfAbsent("apple", 100);
System.out.println("第一次添加 apple: " + result1); // 输出: null
System.out.println("Map: " + map); // 输出: {apple=100}

// 第二次尝试添加相同的 key - key 已存在
Integer result2 = map.putIfAbsent("apple", 200);
System.out.println("第二次添加 apple: " + result2); // 输出: 100
System.out.println("Map: " + map); // 输出: {apple=100}

// 添加新的 key
Integer result3 = map.putIfAbsent("banana", 150);
System.out.println("添加 banana: " + result3); // 输出: null
System.out.println("Map: " + map); // 输出: {apple=100, banana=150}
```

是否存在key或者value

1
2
map.containsKey()
map.containsValue()

获取key对应的值,如果没有key,则设置默认值1

1
getOrDefault(1)

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

1
int new_value = map.compute(1, (key, value) -> value +1 );

评论