问题
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