Is there a more concise way to do this in Java 8 - Map manipulation

后端 未结 2 1223
迷失自我
迷失自我 2021-01-20 23:27

A very common operation on maps of collections is to create a new collection with an initial value when the key is not present, or if the key is present, do some function on the

2条回答
  •  无人共我
    2021-01-21 00:12

    Here's another alternative:

    Set set = m.computeIfAbsent (key , k -> new HashSet<> ());
    set.add(set.size() + 1);
    

    The only reason this is a two liner (instead of one) is the need to obtain the current size of the Set in order to decide which value to add to it.

提交回复
热议问题