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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With