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
rohitrrohitr 

Set to String

Hi Guys,

 

I've a set with single element.

I need to get the value in the set to a string.

public Set<String> closeMonthDateSet;

 

The closeMonthDateSet set will have a single value which i need to put into a string.

 

Can anyone help me on this?

Best Answer chosen by Admin (Salesforce Developers) 
DipakDipak

If you are sure that always that set contains 1 single String value...
then you can do like below

String myString;
if(closeMonthDateSet != NULL && closeMonthDateSet.size()>0){

    myString = closeMonthDateSet.get(0);
}

Now the myString contains the 1st String value present in that Set

All Answers

ForcepowerForcepower
You can just iterate through it and get the last value:
Set<String> closeMonthDateSet = new Set<String>{'abc'};

String closeMonthDate;
for (String s: closeMonthDateSet) {
closeMonthDate = s;
}
DipakDipak

If you are sure that always that set contains 1 single String value...
then you can do like below

String myString;
if(closeMonthDateSet != NULL && closeMonthDateSet.size()>0){

    myString = closeMonthDateSet.get(0);
}

Now the myString contains the 1st String value present in that Set

This was selected as the best answer
sfdcfoxsfdcfox
String myString = closeMonthDateSet!=null?String.format('{0}',
  new string[] { string.join(new list<string>(closemonthdateset),'') }):'';

Another alternative might look like this code. While not necessarily the shortest code to read, it counts as only one line of execution.