[SalesForce] String concatenation in a for loop

Need help writing this piece of logic…

Address is a value object in my code. It has a set of variables with get;set;
I get list of Address and I need to iterate the list, get the variables out of the first object in the list and put in a string(var1+var2+…).. As a final output I need a concatenated string of string[0] + string [1] ….string[i] (i being the size of the list)..

For ex: my address object is

public Address() {
    public string street {get;set;}
    public string city{get;set;}
}

I have a list of address Address[] addList = new List<Address>(); the size of the list is 3 in this example

Need to iterate the list and get object out of it.

for(Address a :addList) {
    String first object txt = a0.street+a0.city;
    String second object txt = a1.street+a1.city;
    String third object txt = a2.street+a2.city;
}

String finaltxt = first object txt + second object txt + third object txt.

Please help!

Regards,
P

Best Answer

Assuming Address has a function public override String toString(), you don't need a loop at all:

String results = String.join(addressList, ',');

Edit:

I should have realized that String.join doesn't use toString(), so you do, indeed, need a loop:

String[] stringList = new String[0];
for(Address item: addressList) {
    stringList.add(String.valueOf(item));
}
String result = String.join(stringList, ', ');
Related Topic