Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java-8

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?

like image 384
zhuguowei Avatar asked May 11 '16 14:05

zhuguowei


1 Answers

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.

like image 123
greg-449 Avatar answered Nov 17 '22 06:11

greg-449