Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to concatenate List of String objects? [duplicate]

Tags:

java

string

list

People also ask

What is the most efficient way to concatenate many strings together?

If you are concatenating a list of strings, then the preferred way is to use join() as it accepts a list of strings and concatenates them and is most readable in this case. If you are looking for performance, append/join is marginally faster there if you are using extremely long strings.

How do I concatenate a list of items in a string?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

How do I concatenate strings multiple times?

Or you can just take advantage of the fact that multiplying a string concatenates copies of it: add a space to the end of your string and multiply without using join . >>>

Can you use a double in string concatenation?

The “+” operator with a String acts as a concatenation operator. Whenever you add a String value to a double using the “+” operator, both values are concatenated resulting a String object. In-fact adding a double value to String is the easiest way to convert a double value to Strings.


Use one of the the StringUtils.join methods in Apache Commons Lang.

import org.apache.commons.lang3.StringUtils;

String result = StringUtils.join(list, ", ");

If you are fortunate enough to be using Java 8, then it's even easier...just use String.join

String result = String.join(", ", list);

Using Java 8+

String str = list.stream().collect(Collectors.joining())

or even

String str = String.join("", list);

Your approach is dependent on Java's ArrayList#toString() implementation.

While the implementation is documented in the Java API and very unlikely to change, there's a chance it could. It's far more reliable to implement this yourself (loops, StringBuilders, recursion whatever you like better).

Sure this approach may seem "neater" or more "too sweet" or "money" but it is, in my opinion, a worse approach.


A variation on codefin's answer

public static String concatStringsWSep(Iterable<String> strings, String separator) {
    StringBuilder sb = new StringBuilder();
    String sep = "";
    for(String s: strings) {
        sb.append(sep).append(s);
        sep = separator;
    }
    return sb.toString();                           
}

If you are developing for Android, there is TextUtils.join provided by the SDK.


This is the most elegant and clean way I've found so far:

list.stream().collect(Collectors.joining(delimiter));

Guava is a pretty neat library from Google:

Joiner joiner = Joiner.on(", ");
joiner.join(sList);