+ Start a Discussion
SoozeeSoozee 

How to convert a Set<String> into a Comma Separated List?

I need to be able to convert the values in a set into a comma separated list so that I can use it in a SOQL query.

Here is the code:

 

        List<GroupMember> getGroups = [SELECT group.name FROM GroupMember WHERE UserOrGroupId =:someID];
        system.debug('after getGroups' +getGroups);

	for (integer i=0;i<getGroups.size();i++){	
			system.debug('Group Name ='+getGroups[i].group.name);
			if (OTHERCLASS.MAP_BY_GROUPNAME.containsKey(getGroups[i].group.name)==true){
				collegeList.add(OTHERCLASS.MAP_BY_GROUPNAME.get(getGroups[i].group.name));				
			}
        }
        system.debug('college list after adding to set'+collegeList);
        // add all to array
        //CollegeListArr.addAll(collegeList);  // this does not work
        system.debug('after adding to array');
        for(integer y=0;y<collegeList.size();y++){
        if(y>0) collegeListArr +=',';  
        collegeListArr += collegeList[y].id; // this does not work
        }
 

If I try to addall, I get an error on the Visual Force page:  unexpected token: '{College Name}'  

If I try the second method, I get 'Illegal Assignment from String to Set<String>'

 

Help?!?!

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox
String collegeString = '';
for(String s:collegeList) {
   collegeString += (collegeString==''?'':',')+s;
}

Sets do not have an index, so you have to use the iterator means of looping through the list.

 

But, if you're using it in a query, you don't need to do this! The "IN" operator automatically works on Set values just as well as making the list yourself. This means the entire loop is unnecessary, as you can just do this:

 

[SELECT ... FROM ... WHERE Id IN :collegeList]

You can also do this with dynamic apex as well:

 

database.query('select ... from ... where id in :collegelist');

I hope this helps you out with your project.

All Answers

sfdcfoxsfdcfox
String collegeString = '';
for(String s:collegeList) {
   collegeString += (collegeString==''?'':',')+s;
}

Sets do not have an index, so you have to use the iterator means of looping through the list.

 

But, if you're using it in a query, you don't need to do this! The "IN" operator automatically works on Set values just as well as making the list yourself. This means the entire loop is unnecessary, as you can just do this:

 

[SELECT ... FROM ... WHERE Id IN :collegeList]

You can also do this with dynamic apex as well:

 

database.query('select ... from ... where id in :collegelist');

I hope this helps you out with your project.

This was selected as the best answer
SoozeeSoozee

Thank you so much for your help!

satish dixitsatish dixit
Nice post.To know other ways refer this link http://techno-terminal.blogspot.in/2015/08/convert-collection-into-comma-separated.html