How to Convert ID to String in Salesforce Apex

While working as a Salesforce developer, I recently converted data types for some object fields. There was a custom object called User_Activity_c. This object has a field Related_record_c to store the record’s ID associated with the activity.

Since the Related_Record__c field is a text field, I had to convert the ID type to a string before storing it. For this, I used the Salesforce Apex inbuilt function recordId.toString().

In the steps below, I will explain how to convert an ID to a string data type in Salesforce Apex.

Convert ID to String in Salesforce Apex

We will use the apex class method to convert an ID to a string in Salesforce Apex. To do so, navigate to the Salesforce developer console and follow the steps below.

  1. To create a new class in the developer console, select File > New > Apex Class.
    • Enter the name of the new apex class and click the OK button.
    • Enter the code below in the developer console and save it.
public class IdToString{
    public static String convertIdToString(Id recordId) {
        String idAsString = String.valueOf(recordId);
        return idAsString;
    }
}
  1. If the code does not throw errors, execute it using the shortcut keys Ctrl+E.
    • In the anonymous window, enter the code below to test the class method and return the output. After entering the code, select the “Open in Debug” checkbox and click the “Execute” button.
Id myRecordId = '006J30000028PIcIAM'; 
String idAsString = IdToString.convertIdToString(myRecordId);

System.debug('Id as String: ' + idAsString);
Convert Id to string in Salesforce apex
  1. In the console log window, select the checkbox to debug only. After this, you will see the ID converted to a string.
Salesforce Apex convert Id to string

This way, we can convert the ID to a string data type in Salesforce Apex by following the steps outlined above.

Convert Set ID to Set String in Apex Code

In Salesforce Apex, we can also convert a set of IDs to a set of Strings using the mapOfSet.values() method. I will explain how to achieve this in the steps below.

  1. In the Salesforce developer console, open the anonymous execution window with the “Ctrl+E” keys. Here, we will execute and test the code.
    • Now, enter the code below in the anonymous window, then select the checkbox Open in Debug” and click the Execute button.
Map<String, Set<String>> mapOfSet = new Map<String, Set<String>> {
    'a' => new Set<String> {'0015i00001DLNzkAAH', '0015i00000lU1hsAAC', '001J3000007zBCnIAM'}
    
};

Map<String, Set<String>> mapOfSet = new Map<String, Set<String>>{
    'a' => new Set<String>{'0015i00001DLNzkAAH', '0015i00000lU1hsAAC', '001J3000007zBCnIAM'}
};

Set<Id> setOfId = new Set<Id>();

for (Set<String> s : mapOfSet.values()) {
    for (String str : s) {
        setOfId.add((Id) str);
    }
}

System.debug('== ' + setOfId);
  1. Let’s break down the code above, where we have converted the Set ID to a Set string in Apex.
  • Map<String, Set<String>> mapOfSet: Initializes a Map with a key ‘a and a set of three String values representing record IDs.
  • Then, a new Set named setOfId is created. This set will store ID values and hold unique Salesforce record IDs of type Id.
  • The For loop with the function mapOfSet.values() iterates over the Map values, converts each String to an Id, and adds it to a Set.
  • Finally, System.debug() prints the contents of setOfId to the debug log. It displays values that were converted from strings.
  1. In the console log window, select the checkbox to debug only. You will then see a set of strings converted from a set of IDs.
Convert Id set to String set in Salesforce Apex

This way, we can convert a set of IDs to a set of strings in Salesforce Apex using the map class.

Convert Set ID to Set String with Deserialization in Salesforce Apex

We can also convert a set ID to a set string without using the for loop, like the above method. In this method, we will use the deserialize and serialize functions to convert an ID set to String Set.

  1. Navigate to the developer and open an anonymous window.
    • Enter the code below in the anonymous window, select the checkbox, and click on the Execute button.
Set<Id> Ids = new Set<Id>{'001J3000007zBCnAAC','0015i00000lU1hsAAC','001J3000007zBCnIAM'};
Set<String> idStrs = (Set<String>)JSON.deserialize(JSON.serialize(ids),
Set<String>.class);
System.debug('idStrings=' +idStrs);
  • In the above code, the ID set is serialized to a JSON string using JSON.serialize() method. Serialization converts the Set into a JSON string array format.
  • After this, the serialized JSON string is deserialized into a Set type.
  1. In the console log window, select the checkbox to debug only, and then you will see the set ID converted to a set string.
How to convert Id to String in Salesforce Apex

This way, we can convert a set ID to a set string in Salesforce Apex using the serialize and deserialize functions.

Set ID to Set String SOQL type conversion in Salesforce Apex

In a SOQL query, we can convert a set ID to a set String; the ID type is automatically handled as a String in SOQL. We can query the ID field and treat it as a String in Apex code.

In the code below, I explain how to convert an ID to a string in SOQL queries.

  1. In the developer console, execute the anonymous code window with “Ctrl+E.”
    • Enter the code below in the anonymous window and click the Execute button.
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 6];

Map<Id, Account> nmap = new Map<Id, Account>(accounts);

List<Id> nmaps = new List<Id>();
nmaps.addAll(nmap.keySet());

String s = '\'';
s += String.join(nmaps, '\',\'');
s += '\'';
System.debug(s);
  • The List<Account> accounts will retrieve the list of account records.
  • The Map function will initialize the list. Then, List<Id> will prepare a list of IDs.
  • String.join will construct the string from the id list.
  1. In the execution log window, select the checkbox to debug only. After this, you will see a set of string records converted from a set of IDs.
Set of id to Set to string in Salesforce Apex SOQL

This way, we can convert the set ID to a set String SOQL type in Salesforce Apex.

Conclusion

In this Salesforce tutorial, we learned to convert an ID to a string in Salesforce Apex. First, we converted a single ID to a string data type. Then, we converted a set of IDs to a set of strings using the Map class.

Finally, we discussed a different approach to converting the set of IDs to a string using the serialize and deserialize methods.

You may also like to read.

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.