Updating a Key’s Value in a HashMap: A Guide

Upon setting the value to null during the update process, consider implementing the following solution: To avoid pairing the same list object for every key in the for loop, use the constructor to create a new object each time. One approach is to utilize the ‘public ArrayList(Collection c)’ method. Here’s a question to consider: What’s the best way to handle a hashmap with integer keys and date lists as values?


Question:

I am having HashMap like this,

HashMap> map = new HashMap>();

Before inserting an element into

map

, I am attempting to accomplish a task.

  1. To verify the presence of

    key

    , I can utilize

    map.containsKey()

    .
  2. In case the key is present, I intend to verify the size of

    Set

    associated with it.
  3. In case I have a set identified as

    size <= 1

    , and I need to include a new element within it.


Solution 1:

Instead of using containsKey and get, it’s better to perform a single lookup operation.

private final Map> map = new HashMap>();
Set set = map.get(key);
if(set != null && set.size() <= 1) 
    set.add(some$value);

The sole issue with this is that the value will consistently remain as

null

unless it is specified at a different location. Hence, what you could be seeking is…

private final Map> map = new HashMap>();
Set set = map.get(key);
if(value != null)
    map.put(key, set = new HashSet());
if (set.size() <= 1) 
    set.add(some$value);

Is there any particular reason for having a set with a maximum size of 2? It’s not a common occurrence.


Solution 2:

Sounds like this:

HashMap> map = new HashMap>();
Set value = map.get("key");
if(value != null) {        
    if(value.size() <= 1) {
        value.add("some value");
    }
} else {
    map.put("key", new HashSet());
}

The last point may have been unclear, but it seems that either you want to modify the Set linked to the key, or you want to modify the key itself by removing it and adding a new entry.


Solution 3:


The set can be obtained from the map using map.get(String key).

Evaluate the dimension of the Set and, if necessary, append your item.

You can easily replace the previous set on the map by calling map.remove(String key) and then inserting a new one using put(String, Set).

Frequently Asked Questions