How to create a string from an array of strings or arraylist?

how can I extract all the elements in the string [] or arraylist and combine all the words with the correct formatting (with one space) between them and save in an array.

String[] a = {"Java", "is", "cool"}; 

Exit: Java is cool.

+7
source share
2 answers

Use StringBuilder .

 String[] strings = {"Java", "is", "cool"}; StringBuilder builder = new StringBuilder(); for (String string : strings) { if (builder.length() > 0) { builder.append(" "); } builder.append(string); } String string = builder.toString(); System.out.println(string); // Java is cool 

Or use Apache Commons Lang StringUtils#join() .

 String[] strings = {"Java", "is", "cool"}; String string = StringUtils.join(strings, ' '); System.out.println(string); // Java is cool 

Or use Java8 Arrays#stream() .

 String[] strings = {"Java", "is", "cool"}; String string = Arrays.stream(strings).collect(Collectors.joining(" ")); System.out.println(string); // Java is cool 
+30
source

My recommendation would be to use org.apache.commons.lang.StringUtils :

 org.apache.commons.lang.StringUtils.join(a, " "); 
+6
source

All Articles