原文链接: A Guide to Java HashMap → https://www.baeldung.com/java-hashmap

HashMap<String, Integer> map = new HashMap<>();
// {}
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
// {Apple=1, Cherry=3, Banana=2}
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Banana", 3);
// {Apple=1, Banana=3}
map.remove("Banana");
// {Apple=1, Cherry=3}
boolean hasOrange = map.containsKey("Orange");
int mapSize = map.size();
map.clear();
// {}
Set<String> keys = map.keySet();
Collection<Integer> values = map.values();
Set<Map.Entry<String, Integer>> entries = map.entrySet();
[Q&A] 平时都使用Map的put方法,但是put方法返回值是啥?
key对应存储的上个值
Map<Object, Boolean> map = new HashMap<>();
Boolean value1 = map.put("key", true);
System.out.println(value1); // null key上个值为null,故返回null
Boolean value2 = map.put("key", false);
System.out.println(value2); // null key上个值为true,故返回true
# 原生方法
Map<String, Integer> map = new HashMap<>();
Integer age6 = map.get("name"); // Integer时返回null可以
int age6 = map.get("name"); // int时返回null报错
Integer age5 = map.getOrDefault("name", 0); // 取不到使用默认值
# MapUtils
Map<String, Integer> map = new HashMap<>();
Integer age1 = MapUtils.getInteger(map, "name"); // Integer时返回null可以
int age3 = MapUtils.getInteger(map, "name"); // int时返回null报错
Integer age1 = MapUtils.getInteger(map, "name", 0); // 取不到返回null
int age3 = MapUtils.getInteger(map, "name", 0); // 取不到返回null
dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
<scope>compile</scope>
/dependency>
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 85);
scores.put("Bob", 95);
System.out.println(scores);
scores.computeIfPresent("Alice", (key, oldValue) -> {
if (oldValue >= 85) {
return oldValue + 5;
}
return oldValue;
});
System.out.println(scores);
// {Bob=95, Alice=85}
// {Bob=95, Alice=90}
Map<Object, Boolean> map = new HashMap<>();
System.out.println(map); // {}
# 1、map不存在key,故返回null,并把当前key,value存储到Map中
Boolean value1 = map.putIfAbsent("key", true);
System.out.println(value1); // map不存在key,故返回null
System.out.println(map); // {key1=true}
# 2、map存在key,故返回对应value,并忽略当前key,value
Boolean value2 = map.putIfAbsent("key", false);
System.out.println(value2); // map存在key,故返回存的true
System.out.println(map); // {key1=true}
[Q&A] 存在的问题:
当key对应的值为null时,调用putIfAbsent返回null无法判断是存在键(key,null),还是key不存在;