简体   繁体   中英

java iterate over map< string, list< string> , getordefault method

I have a map of < string, List< String type>>, What I am trying to do is add a string to map value if list is present, else create a list and add it to the list and insert in map . s1 , s2 are strings.

Code:

Map<String, List<String>> map = new HashMap<>();

map.put(s1,(map.getOrDefault(s1, new LinkedList<String>())).add(s2));

Error:

error: incompatible types: boolean cannot be converted to List<String>

What's wrong with this !!!

add method of list 'map.getOrDefault(s1, new LinkedList())).add(s2)' is return boolean so you have to do it in separate line

so try like this

    Map< String, List< String>> map = new HashMap<>();

    List<String> list = map.get(s1);
    if(list == null){
      list = new LinkedList<>();
      map.put(s1,list);
    }
    list.add(s2);

If use java 8 and need to do in single line do like this

    map.computeIfAbsent(s1, k -> new LinkedList<>()).add(s2); 

This call,

(map.getOrDefault(s1, new LinkedList())).add(s2)

Returns a boolean primitive, which can not be casted to a List . That why you are getting this error.

You can solve it like so,

map.compute(s1, (k, v) -> v == null ? new LinkedList<>() : v).add(s2);

The trick here is, map.compute() returns the new value associated with the specified key, and then you can add the s2 String literal into that afterward.

Map<String, List<String>> map = new HashMap<>();

// gets the value if it is present in the map else initialze the list
List<String> li = map.getOrDefault(s1,new LinkedList<>());

li.add(s2);

map.put(s1,li); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM