Reputation: 943
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
,
key
exist or not, i can get it by using map.containsKey()
.Set
respective to that key.size <= 1
i want add an element in that set.Upvotes: 1
Views: 23763
Reputation: 62439
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.
Upvotes: 3
Reputation: 533520
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?
Upvotes: 3
Reputation: 138
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);
Upvotes: 1