0

I have a

Map<Id,Set<String>>

In my code.

I have a loop structured as this:

for(value : data) {

     for(String string : Map.get(value) {

       //Do something
   }
}

When I do this am I actually looping through the strings within the Set or is it simply returning the sets themselves as a string. But not like when I do something like this:

Set<String> TestSet = new Set<String>();
TestSet = Map.Get(somevalue)

Might be an obvious answer but I can't seem to find any confirmation on this.

1 Answer 1

1

In that snippet you're looping through the Set's elements.
You could take a look at documentation about for loops.

for (variable : list_or_set) {
        code_block
}

When executing this type of for loop, the Apex runtime engine assigns variable to each element in list_or_set, and runs the code_block for each value.

By the way, I would suggest to always check the result of map.get() before iterating over it, unless you're 100% sure there is an element paired with that key.
Doing for(String string : Map.get(value)) { will expose to a NullPointerException: if the map doesn't cointains that key, it will return null leading to a NPE.
A safer option would be:

Set<String> variable = Map.get(value);
if (variable != null) {
    for (String s : variable) {
        do something
    }
}

This way your code is more robust and will not raise a NullPointerException.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .