How to update a value for a key in HashMap?
Solution 1
I wouldn't use containsKey and get as this means two lookups when you only need one.
private final Map<String,Set<String>> map = new HashMap<String,Set<String>>();
Set<String> set = map.get(key);
if(set != null && set.size() <= 1)
set.add(some$value);
The only problem with this is that the value will always be null
unless you set it somewhere so what you may want is
private final Map<String,Set<String>> map = new HashMap<String,Set<String>>();
Set<String> set = map.get(key);
if(value != null)
map.put(key, set = new HashSet<String>());
if (set.size() <= 1)
set.add(some$value);
It is unusual to have a set with a maximum size of 2. Is there any reason for this?
Solution 2
Sounds like this:
HashMap<String,Set<String>> map = new HashMap<String,Set<String>>();
Set<String> value = map.get("key");
if(value != null) {
if(value.size() <= 1) {
value.add("some value");
}
} else {
map.put("key", new HashSet<String>());
}
Now, either the last point was poorly worded (i.e. you want to update the Set associated with the key) or you really want to update the key itself, in which case you'd probably have to just remove it and add a new entry.
Solution 3
You could get the set from the map with map.get(String key).
Then test the size of the Set. If needed, add your element.
Now you can simply remove the old set from the map with map.remove(String key) and reinsert it with put(String, Set);
Vinesh
Updated on September 26, 2020Comments
-
Vinesh almost 4 years
I am having HashMap like this,
HashMap<String,Set<String>> map = new HashMap<String,Set<String>>();
I am trying to do before adding an element in
map
,- Want to check whether the
key
exist or not, i can get it by usingmap.containsKey()
. - If the key exist, i want check the size of
Set
respective to that key. - If
size <= 1
i want add an element in that set.
-
Dominik Sandjaja almost 12 years
if (map.containsKey("x")) {Set<String> s = map.get("x"); if (s.size() <= 1) { s.add("y");}}
(oh, just misread that the key should be updated - why?!) -
Luiggi Mendoza almost 12 yearsWhy would you want to update the key? You can't and you shouldn't think on do it
- Want to check whether the
-
David Grant almost 12 yearsI know the OP asked for it, but it would make more sense if value.size() was being compared with 0. But have an upvote anyway ;)
-
Tudor almost 12 years@David Grant: You mean
== 0
instead of<= 1
? -
Tudor almost 12 years@David Grant: Dunno what he actually wants to do here. It's possible he wants to add something if the size is 0 or 1. I just left his original code.
-
Fildor almost 12 yearsWould it improve something to just
map.get(key)
and then check for null, since I guess if there is no such key it should be added, right? -
Tudor almost 12 years@Fildor: Yeah, I guess it would be more efficient, since only a single lookup is done.
-
Vinesh almost 12 yearsI want to store only 2 values for a key... So i have set with a maximum size of 2.