0

Can I convert an array to a string in apex? Is string valueOf() method an efficient way to convert it?

2 Answers 2

6

I think String.join() method is what you are looking for, since it

Joins the elements of the specified iterable object, such as a List, into a single String separated by the specified separator.

For instance

List<String> elements = new List<String>{ 'one', 'two', 'three' };
String.join(elements, ''); // 'onetwothree'
4

It rather depends on the purpose of the conversion, but an efficient and controllable means is to use String.join as mentioned by @Oleh Berehovskyi. Here you can choose an appropriate separator, similar to Oleh's example:

List<String> elements = new List<String>{ 'one', 'two', 'three' };
String.join(elements, ', '); // 'one, two, three'

If you are interested in JSON structuring of the array, you can use JSON.serialize instead, which would result in something like:

List<String> elements = new List<String>{ 'one', 'two', 'three' };
JSON.serialize(elements); // ["one","two","three"]

This is easy to parse again using JSON.deserialize.

The String.valueOf(elements) and elements.toString() approaches are other options that generate their own formats. However, these tend to be less useful since you cannot control the format and they are not easily parsed in general terms (if you have a need to do so).

I haven't compared performance for each of these, but you can see you could easily do so with some anonymous apex.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .