3

I am trying to iterate over and display a Map<String,List<string>> in a visualforce page. I understand that I probably need to switch to a inner / wrapper class. But first, I want to make sure that the map is populating properly, as what I'm seeing when passing the maps values to system.debug seems strange to me, so want to validate.

The keyset is clearly populating correctly, and is displaying fine on the visualforce page. Its the values which look, to my eyes, like the previous lists are being blanked out when a new one is added.

I'll insert the screenshot of the debug log first, and then some of the relevant code

Screenshot of debug log - see how the previous set of values do not appear in the next step of the log screenshot of debug

Code Snippet:

map<string,list<string>> ApproverGroupMap = new map<string,list<string>>();
private void populateLists(){

        FOR (group g : grouplist){
            integer groupsize = 0;
            list<string> activeGroupMembers = new list<string>();
            FOR(groupmember gm : g.groupMembers){
                IF(activeUserIds.contains(gm.UserorGroupId)){
                    groupsize ++;
                    string un = umap.get(gm.UserorGroupId).name;
                    activeGroupMembers.add(un);
                }
            }
            system.debug('activegroupmembers.size - ' + activegroupmembers.size());
            approverGroupMap.put(g.Name,activeGroupMembers);
            system.debug('approvergroupmap keyset = ' + approverGroupMap.keySet());
            system.debug('approvergroupmap values = ' + approverGroupMap.values());

            IF(groupsize == 0){
                emptygrouplist.add(g.Developername);
            }
            activeGroupMembers.clear();
        }
2

Nice job on using the debug log to expose the problem.

The cause is this:

activeGroupMembers.clear();

in that you are emptying out the list that you have added a reference to in the map. Without that it should work. You are already correctly creating a new list for every map entry via this line:

list<string> activeGroupMembers = new list<string>();

These collections work by reference in that what goes into the map isn't a copy of the list but is just a reference (pointer) to the list. So any later modification to the list affects the map too.

| improve this answer | |
  • Thanks works perfectly and am now even able to display the data from the map reasonably well in the visualforce page, well enough for my purposes. – gorav Jul 16 '16 at 23:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.