Convert Set data into String

|
| By Webner

Introduction

When working with sets in apex sometimes we need to create a string from the set’s values but there is no function that can convert a set into a string as we have for lists. To convert set into a string we can use these two approaches

1. Using Loop

In this approach, we loop over the set’s data and put it into a string.

Set<String> setdata = new Set<String>{‘T1’, ‘T2’, ‘T3’, ‘T4’};
String setStringLoop = ”;
for(String eachElement : setdata){
setStringLoop += eachElement + ‘,’;
}
setStringLoop = setStringLoop.substring(0,setStringLoop.length()-1);
system.debug(setStringLoop);

2. Converting Set into String

In this approach, we convert set into a string and manipulate it.

Set<String> setdata = new Set<String>{‘T1’, ‘T2’, ‘T3’, ‘T4’};
String setString = string.valueof(setdata).replace(‘{‘, ”).replace(‘}’, ”);
System.debug(setString == ‘ + setString );

The best approach is the 2nd approach because it reduces the computation time.

Leave a Reply

Your email address will not be published. Required fields are marked *