function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Scott Spilker 12Scott Spilker 12 

Duplicate values in For Loop when iterating on List to create Map

Hi,

I am trying to iterate through a list of users using a For loop, but am receiving duplicate values when pushed to json.

The ID for Username 7 in my example is copied to all values, even though the username shows up correctly in the JSON.

Why is it pushing idForUser7 to all of them here?

{
  "username 1" : {
    "id" : "idForUser7"
  },
  "username 2" : {
    "id" : "idForUser7"
  },
  "username 3" : {
    "id" : "idForUser7"
  },
  "username 4" : {
    "id" : "idForUser7"
  },
  "username 5" : {
    "id" : "idForUser7"
  },
  "username 6" : {
    "id" : "idForUser7"
  },
  "username 7" : {
    "id" : "idForUser7"
  }
}

As a side note, the reason I am going with this approach is to avoid the attributes/type/url when pushing an SObject Map to json.

"attributes" : {
"type" : "User",
"url" : "/services/data/v49.0/sobjects/User/0053t000007t21nAAA"
},
public static string getActiveUsers() {
 		
        Map<string, Map<String, String>> userActiveMap = new Map<string, Map<String, String>>();
        Map<String, String> userActiveMapValue = new Map<String, String>();
        
        try{
            
			for(List<User> activeUsersList : [ select id,username,LastLoginDate,ProfileId from User where IsActive = True]) {
                
                for (User u : activeUsersList) {
                    
                    userActiveMapValue.clear();
                    
                    userActiveMapValue.put('id', string.valueof(u.id));
                    
                    userActiveMap.put(  string.valueof(u.Username) , userActiveMapValue);
                     
                }
                
            }
        
        	
            
         } catch(DmlException e) {
            	System.debug('An unexpected error has occurred: ' + e.getMessage());
         }
            
        return json.serialize(userActiveMap);
        
    }

 
Best Answer chosen by Scott Spilker 12
Maharajan CMaharajan C
Hi Scott,

Try the below code:
 
public static string getActiveUsers() {
 		
        Map<string, Map<String, String>> userActiveMap = new Map<string, Map<String, String>>();
        
        try{
            
			for(User activeUsersList : [ select id,username,LastLoginDate,ProfileId from User where IsActive = True]) {
                
                    Map<String, String> userActiveMapValue = new Map<String, String>();
                    
                    userActiveMapValue.put('id', string.valueof(activeUsersList.id));
                    
                    userActiveMap.put(  string.valueof(activeUsersList.Username) , userActiveMapValue);
            }
        
        	system.debug('userActiveMap==> ' + json.serialize(userActiveMap));
            
         } catch(DmlException e) {
            	System.debug('An unexpected error has occurred: ' + e.getMessage());
         }
            
        return json.serialize(userActiveMap);
        
    }

Thanks,
Maharajan.C

All Answers

Maharajan CMaharajan C
Hi Scott,

Try the below code:
 
public static string getActiveUsers() {
 		
        Map<string, Map<String, String>> userActiveMap = new Map<string, Map<String, String>>();
        
        try{
            
			for(User activeUsersList : [ select id,username,LastLoginDate,ProfileId from User where IsActive = True]) {
                
                    Map<String, String> userActiveMapValue = new Map<String, String>();
                    
                    userActiveMapValue.put('id', string.valueof(activeUsersList.id));
                    
                    userActiveMap.put(  string.valueof(activeUsersList.Username) , userActiveMapValue);
            }
        
        	system.debug('userActiveMap==> ' + json.serialize(userActiveMap));
            
         } catch(DmlException e) {
            	System.debug('An unexpected error has occurred: ' + e.getMessage());
         }
            
        return json.serialize(userActiveMap);
        
    }

Thanks,
Maharajan.C
This was selected as the best answer
David Zhu 🔥David Zhu 🔥
Put method of Map assigns the data reference to the key.  the code creates a instance of userActiveMapValue  in line, it only clears the map on line 12. It ever re-instanitiates userActiveMapValue   after assignment. So, in the memory, all map values are pointing to the same instance of userActiveMapValue. That is why you always get the last id.

To fix this issue, you may need to change line 12 to:
userActiveMapValue = new Map<String, String>();
Scott Spilker 12Scott Spilker 12
Thank you for the answer.  That worked.