Mount a single string with multiple strings from a Java Arraylist

Asked

Viewed 1,630 times

5

How can I take several Strings of an Arraylist in a simplified way and join in only one String type variable? I’m new to Java and I’m having difficulty completing this change in a simplified way, avoiding long lines of code and no need.

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

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

This should look like my String variable:

String fields = "Campo1 Campo2 Campo3";

3 answers

5


Use the method Join() class String:

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

Note: You need JAVA 8

  • If it is using java 8 all right. Otherwise it will not work. You could include this detail in your reply :)

  • @Edgarmunizberlinck Yes, I was now editing to link to the documentation. I will however make this clear.

  • I wasn’t using Java 8 Support, I just implemented it in my Eclipse: http://download.eclipse.org/eclipse/updates/4.3-P-builds/.

  • @ramaral wants to incorporate my answer into yours and I erase?

  • @Maiconcarraro Delete why? Your answer is valid(I voted for it), I think you should keep it.

  • @ramaral Because the author has already marked yours as correct, so if you incorporate mine in yours is a valid answer for anyone with the same problem :)

  • @Maiconcarraro AP marked mine as the accepted answer, the one that best served for him, does not mean that only she is correct or that is the best. Someone who is not using JAVA 8 will read your answer and it will be yours that will serve you and will certainly vote for them. If I incorporate your answer into mine I will receive all the credits which would not be fair. What best indicates whether an answer is good or not is the number of votes you received and not the acceptance mark.

Show 2 more comments

4

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

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

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


Don’t concatenate the strings that way s1 + s2

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

2

Or you can make a loop:

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

Or you can use Stringutils, which is on Commons-lag

listString = StringUtils.join(list, " ");
  • In concatenations within loops one should use Stringbuilder or Stringbuffer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.