Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add values to a Set inside a Map? [closed]

I have this map Map<String, Set<Integer>> myMap;, now I need to interact with it, how do I do it?


for example:

Keys are: "apple", "orange", "grape", etc.
Each set will contain random numbers: 1-9

I need to create a Map (HashMap or TreeMap) that has Strings for keys and sets for the values. I need to return the set given a key. I also need to be able to fill each set with multiple numbers based on a key. Not sure how to approach this problem. Any thoughts?

like image 783
user2242203 Avatar asked Apr 03 '13 20:04

user2242203


People also ask

How do you add value to a map set?

Adding Values to a Map You can add values to a map with the set() method. The first argument will be the key, and the second argument will be the value. This example looks similar to a regular object with string-based keys, but we can use any data type as a key with Map.

How do I add a value to a map in Salesforce?

If you want to add a map onto existing map, use putAll() method. finalMap. get('DETAILS'). putAll(subDetails);

Can we use set inside map?

Your map should be a Map<String,Set<Integer>> , as for the map or the set themselves, refer to the documentation. In particular the methods put and get for the map and the add method for the set. You might want to check out the SetMultimap interface and its implementations from the Guava open source library.

Can we update value in map?

The replace(K key, V value) method of Map interface, implemented by HashMap class is used to replace the value of the specified key only if the key is previously mapped with some value. Parameters: This method accepts two parameters: key: which is the key of the element whose value has to be replaced.


2 Answers

Something to keep in mind is that the value will initially be null, so the first time you use a key, you'll have to initialize it:

Map<String,Set<Integer>> map;  

To add a number to the key, you must do this:

String key = "apple"; // for example 

Set<Integer> set = map.get(key); 
if (set == null) {
    set = new HashSet<Integer>();
    map.put(key, set);
}
set.add(5);

Unfortunately, everywhere you interact with the set, you must null check. For example, if you want to check if a certain key had a certain number mapped to it, you couldn't safely do this:

if (map.get(key).contains(number))  // not safe

because the call to get() may return null (if there's no entry for the key) and you'd get a NullPointerException.

There is a way to make your map very convenient to use by internalising the null check inside the map, so that a call to get() will always return a non-null set; create an anonymous class that overrides get() accordingly:

Map<String,Set<Integer>> map = new HashMap<String,Set<Integer>> () {
    @Override
    public Set<Integer> get(Object key) {
        Set<Integer> set = super.get(key); 
        if (set == null) {
            set = new HashSet<Integer>();
            put(key, set);
        }
        return set;
    }
}

With this in place, your main code becomes a lot simpler and clearer. To add:

map.get(key).add(number);

To check:

if (map.get(key).contains(number)) // now safe

The null checking code is no longer necessary.

——

Java 8 update:

To deal with the null entry problem when adding to the set:

map.computeIfAbsent( key, k -> new HashSet<>() ).add(number);

and for null safe checking:

if ( map.getOrDefault(key, Collections.emptySet() ).contains(number))
like image 133
Bohemian Avatar answered Sep 27 '22 18:09

Bohemian


Not difficult if I understand correctly.

Map<String, Set<Integer>> reqdMap = new HashMap<String, Set<Integer>>();

//Form the set corresponding to apple.
Set<Integer> appleSet = new HashSet<Integer>();
appleSet.add(1);
...


reqdMap.put("apple", appleSet);

//To Retrieve
appleSet = reqdMap.get("apple");
like image 33
prashant Avatar answered Sep 27 '22 17:09

prashant