java8 map how to add some element to a list value simply [duplicate]

守給你的承諾、 提交于 2020-06-26 04:27:20

问题


I want to use Map<String, List<String>> to record something, e.g. each city have how many users of some kind .

Now my code is

    Map<String, List<String>> map = new HashMap<>();
    if(map.get("city_1")==null){
        map.put("city_1", new ArrayList<>());
    }
    map.get("city_1").add("aaa");

but I feel it's a little cumbersome, I want this effect

    Map<String, List<String>> map = new HashMap<>();
    map.compute("city_1", (k,v)->v==null?new ArrayList<>():v.add("aaa"));

but it has compile error:

Type mismatch: cannot convert from boolean to List<String>

So have any other manner could simplify it?


回答1:


Use computeIfAbsent:

map.computeIfAbsent(work, k -> new ArrayList<>()).add("aaa");

Which stores a new list in the map if it does not already exist and returns the new or existing list.



来源:https://stackoverflow.com/questions/37165934/java8-map-how-to-add-some-element-to-a-list-value-simply

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!