Assemble a single string with several strings of an ArrayList in Java

5

How can I get multiple Strings from an ArrayList in a simplified way and merge into just one string variable? I'm new to Java and I'm having trouble completing this change in a simplified way, avoiding long, unnecessary lines of code.

 List<String> fields_list = new ArrayList<String>();

 Saída: ["Campo1, Campo2, Campo3"]

This should be my String variable:

String fields = "Campo1 Campo2 Campo3";
    
asked by anonymous 17.06.2015 / 22:21

3 answers

5

Use the join () of the String class:

String fields = String.join(" ", fields_list);

Note: Requires JAVA 8

    
17.06.2015 / 22:34
4

Use StringBuilder to group your values and for iterate over the list, for example:

StringBuilder sb = new StringBuilder();
for (String s : fields_list)
{
    sb.append(s);
    sb.append(" ");
}

System.out.println(sb.toString().trim());


Do not concatenate strings in this way s1 + s2

In this way, for each concatenated one, the compiler generates a new instance of StringBuilder implicitly, so the best way is to use only 1 as the example.

    
17.06.2015 / 22:28
2

Or you can loop:

String listString;
for (String s : list)
{
    listString += s + " ";
}

Or you can use StringUtils, which is located in commons -lag

listString = StringUtils.join(list, " ");
    
17.06.2015 / 22:29