Reputation: 33
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 !!!
Upvotes: 3
Views: 7333
Reputation: 1
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);
Upvotes: 0
Reputation: 21124
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.
Upvotes: 1
Reputation: 1042
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);
Upvotes: 10