hashMap常用方法
清空hashMap
输出Key
1 2 3 4 5
| for (Integer i : Sites.keySet()) { System.out.println("key: " + i + " value: " + Sites.get(i)); }
|
输出value
1 2 3 4 5
| for(String value: Sites.values()) { 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
|
``` HashMap<String, Integer> map = new HashMap<>();
Integer result1 = map.putIfAbsent("apple", 100); System.out.println("第一次添加 apple: " + result1); System.out.println("Map: " + map);
Integer result2 = map.putIfAbsent("apple", 200); System.out.println("第二次添加 apple: " + result2); System.out.println("Map: " + map);
Integer result3 = map.putIfAbsent("banana", 150); System.out.println("添加 banana: " + result3); System.out.println("Map: " + map); ```
|
是否存在key或者value
1 2
| map.containsKey() map.containsValue()
|
获取key对应的值,如果没有key,则设置默认值1
compute:如果 key 对应的 value 不存在,则返回该 null,如果存在,则返回通过 remappingFunction 重新计算后的值。
1
| int new_value = map.compute(1, (key, value) -> value +1 );
|