Vinesh
Vinesh

Reputation: 943

How to update a value for a key in HashMap?

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,

  1. Want to check whether the key exist or not, i can get it by using map.containsKey().
  2. If the key exist, i want check the size of Set respective to that key.
  3. If size <= 1 i want add an element in that set.

Upvotes: 1

Views: 23763

Answers (3)

Tudor
Tudor

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

Peter Lawrey
Peter Lawrey

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

sabre_raider
sabre_raider

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

Related Questions