9

how can i extract all the elements in a string [] or arraylist and combine all the words with proper formating(with a single space) between them and store in a array..

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

Output: Java is cool.

2 Answers 2

33

Use a 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's Arrays#stream().

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

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

org.apache.commons.lang.StringUtils.join(a, " ");
3
  • Can you please explain how can I import this in a project in Netbeans. Commented Jun 1, 2013 at 19:12
  • Not reinventing the wheel. So I would also suggest this method. Commented May 28, 2015 at 10:58
  • The org.apache.commons link is dead. Commented Jul 4, 2016 at 8:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.