简体   繁体   English

java迭代map <string,list <string>,getordefault方法

[英]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 . 我有一个<string,List <String type >>的映射,我想要做的是如果列表存在则添加一个字符串来映射值,否则创建一个列表并将其添加到列表并插入map s1 , s2 are strings. s1s2是字符串。

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 添加列表'map.getOrDefault(s1,new LinkedList())的方法.add(s2)'是返回布尔值,所以你必须在单独的行中执行

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 如果使用java 8并且需要在单行中做这样的事情

    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 . 返回一个boolean元,无法将其转换为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.compute()返回与指定键关联的新值,然后您可以在之后添加s2字符串文字。

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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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