Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a string from string array or arraylist?

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.

like image 454
user647207 Avatar asked May 08 '11 03:05

user647207


2 Answers

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
like image 65
BalusC Avatar answered Oct 27 '22 01:10

BalusC


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

org.apache.commons.lang.StringUtils.join(a, " ");
like image 30
RHSeeger Avatar answered Oct 26 '22 23:10

RHSeeger