简体   繁体   中英

How do I join a String[] without a delimiter in Java 8?

There are lots of questions about how to join a String[] in Java 8 with a delimiter, but how should a String[] be joined without a delimiter?

For example, {"a", "b", "c"} becomes "abc" .


Note: I know how to write a small function for this myself, so please do not leave custom solutions. I am looking for a one-liner from the standard library.

public class Test {
    public static void main(String[] args) {
        System.out.println( String.join("", new String[]{"a", "b", "c"}) );
}}

Outputs: abc

The relevant part being String.join("", arrayStrings);

Javadoc for String.join

Adding to what has already been said, you can even do it as simple as this if you so prefer:

public class Test {
    public static void main(String[] args) {
        System.out.println(String.join("", "a", "b", "c"));
    }
}

Ie you don't even have to wrap it in an array; since String.join takes a ... (variable argument), you can just specify any number of String arguments without explicitly wrapping them in an String[] object.


Note : the big disadvantage of the approach above is that it obscures the distinction between the delimiter and the delimited strings; @Aaron's answer is generally preferable. But anyhow, it deserves to be mentioned that you can actually write it like this also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM