Home  >  Article  >  Java  >  How to Concatenate Elements of a String Array in Java: Equivalent to PHP\'s join() Function?

How to Concatenate Elements of a String Array in Java: Equivalent to PHP\'s join() Function?

DDD
DDDOriginal
2024-10-29 02:53:30888browse

How to Concatenate Elements of a String Array in Java: Equivalent to PHP's join() Function?

Java Equivalent of PHP's Join Function for Arrays

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn