Problem:
You need to concatenate elements of a String array using a delimiter, similar to PHP's join() function.
Solution:
Java 8 and Later:
Starting from Java 8, you can use the built-in String.join() method:
<code class="java">String.join(", ", new String[] {"Hello", "World", "!"})</code>
This will generate:
Hello, World, !
Java 7 and Earlier:
For earlier versions of Java, you can use the StringUtils class from Apache Commons Lang:
<code class="java">StringUtils.join(new String[] {"Hello", "World", "!"}, ", ")</code>
This will also generate the string:
Hello, World, !
Note: The StringUtils.join() method is more versatile and supports additional features, such as customizing the separator character and handling null elements.
The above is the detailed content of How to Concatenate Elements of a String Array in Java: Equivalent to PHP's join() Function?. For more information, please follow other related articles on the PHP Chinese website!