JFed
JFed

Reputation: 17

Returning entryset in map using key value

I have two string value ID and Value coming from my code, I need to store this in a map without iterating over the map but by checking by the key value if it exists in the map. The ID can come many times with different value and in that case I have add it to the already existing entry of the ID and add the value along with the existing value

I created a Map with String and List to add the values but I am facing difficulties,

Map < String, List< String >> accessMap = new HashMap < String, List< String>>();

If the key is not present, add a new entry with ID and Value (as List).

How to find the key in the map and get the entrySet without iterating over the map and add the value alone, if the ID is already present in the map.

Example,

while(accessList.hasNext()){


....


....

String id = accessEntry.get(ID);

String value = accessEntry.get(Value);


/*Add the id and value to the map if not present, if ID is present add the    *value alone to the entrySet.Value (which is a list)
*/

}

The id and value has to be added into a map checking if the ID is already present in the map, if not create a new entry.

The accessList might have many ID references with different value, in that case the value should be added to the entrySet of the already existing entry, the value would be a list with single value or multiple value.

Upvotes: 1

Views: 379

Answers (2)

Bohemian
Bohemian

Reputation: 425043

Use computeIfAbsent() to initialise a List for the id if one doesn't exist already, then just add the value to that:

entitlementMap.computeIfAbsent(id, s -> new ArrayList<>()).add(value);

Upvotes: 0

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

public static void add(Map<String, Set<String>> map, String key, String value) {
    map.compute(key, (id, values) -> {
        (values = Optional.ofNullable(values).orElseGet(LinkedHashSet::new)).add(value);
        return values;
    });
}

For values it is better to use Set to exclude duplications.

Upvotes: 1

Related Questions