Map map = Maps.newHashMap();
map.put("xx","xx");
System.out.println(map.getOrDefault("x","返回默认"));
getOrDefault: 如果指定的key存在,返回value,不存在,返回指定的值
Map map = Maps.newHashMap();
map.put("xx","xx");
map.putIfAbsent("xx","xx1");
System.out.println(map.get("xx"));
putIfAbsent: 如果key关联的value不存在,则关联新的value值,返回key关联的旧的值 ,上面的例子输出的是“xx”。
Map map = Maps.newHashMap();
map.put("xx","xx");
map.computeIfAbsent("xx", key -> key + "1");
map.computeIfAbsent("xx2",key -> key + "2");
System.out.println(map.get("xx"));
System.out.println(map.get("xx2"));
computeIfAbsent: 如果指定的key不存在,则通过指定的K -> V计算出新的值设置为key的值 ,上面的例子输出的是"xx","xx2".
Map map = Maps.newHashMap();
map.put("xx","xx");
map.computeIfPresent("xx",(key,value)-> key + value);
map.put("xx2","xx2");
map.computeIfPresent("xx2",(key,value)->null);
System.out.println(map.get("xx"));
System.out.println(map.get("xx2"));
computeIfPresent: 如果指定的key存在,则根据旧的key和value计算新的值newValue; 如果newValue不为null,则设置key新的值为newValue, 如果newValue为null,则删除该key的值 ;上面的例子输出的是"xxxx",null.