increaseValue 方法我需要增加它的值。在方法中,我检查值是否存在,如果没有,我初始化它并增加它。
increaseValue
private final Map<String, AtomicInteger> map = new ConcurrentHashMap<>(); public void increaseValue(String key) { map.putIfAbsent(key, new AtomicInteger(0)); map.get(key).incrementAndGet(); }
据我所知,在Java11中,这两个操作可以在一行中完成,不是吗?
即使在Java8中,它仍然是可能的。突出使用 computeIfAbsent()
computeIfAbsent()
map.computeIfAbsent(key, k -> new AtomicInteger(0)).incrementAndGet();
根据 computeIfAbsent
computeIfAbsent
退换商品 : 与指定键关联的当前值(现有值或计算值),如果计算值为null,则为null