How to Convert List to String in Salesforce Apex

While working as a Salesforce system administrator, I managed orders within our Salesforce organization. Each order contains multiple product names stored in a list.

To send an email to the customer, I need to convert the list of product names into a single string with commas separating each item.

In this Salesforce tutorial, I will explain convert a list to a string in Apex using all possible methods.

Convert List to String Using String.join() Method in Salesforce Apex

In Salesforce Apex, the easiest way to convert a list to a string is by using the String.join() method. This method joins a list of strings using a specified separator (in this case, a comma).

Now, navigate to the Salesforce developer console and follow the steps below.

  1. In the developer console, launch the anonymous window, enter the code below, and click the Execute button.
List<String> strList = new List<String>{'Generator 200wt', 'Generator 600wt', 'Generator 1000wt'};
String result = String.join(strList, ',');
System.debug(result);
  1. In the execution log window, select the checkbox to debug only. Then, in the debug output, the strings will be converted from a list.
Convert list to string in Salesforce apex

This way, we can convert the list to a string in Salesforce Apex using the string.join() method.

Convert List to String using For Loop in Salesforce Apex

To convert the list to a string in Salesforce Apex using a for loop, we need to manually iterate over the list and append each element to a string variable.

Now, navigate to the developer console and follow the steps below.

  1. Launch the anonymous Apex window, enter the code below, and click Execute.
List<String> strList = new List<String>{'Generator 200wt', 'Generator 600wt', 'Generator 1000wt'};
String result = '';
for(String str : strList) {
    result += str + ','; // Adding a separator
}
result = result.removeEnd(','); 
System.debug(result); 
  1. In the execution log window, select the checkbox to debug only. In debugging, the output will return as a single string value from a list.
Salesforce apex convert list to string

This way, we can convert a list to a string using the for loop in Salesforce Apex.

Convert List to String using JSON.serialize() method in Salesforce Apex

To convert a List to a String using JSON.Serialize () method in Salesforce Apex, open the developer console, and follow the steps below.

  1. In the Salesforce developer console, open the Execute Anonymous window, enter the code below, and click the Execute button.
List<String> strList = new List<String>{'Electric Motor', 'Electric Transformer', 'Solar inverter'};
String result = JSON.serialize(strList); 
System.debug(result); 
  1. In the Execution log window, the output will return as a string in debug.