5

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

1
  • 1
    Can you please update your question and provide some code snippets? By doing that you'll get a better answer Commented Feb 24, 2015 at 22:43

2 Answers 2

13

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, ', ');
1
0
String finaltxt='';
for(Address a :addList) {
    finaltxt+=a.street;
    finaltxt+=' ';
    finaltxt+=a.city;
    finaltxt+=',';
}
finaltxt=finaltxt.subString(0,finaltxt.length()-1);

You must log in to answer this question.

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