"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Combine Array Elements into a String in Java: A PHP join() Equivalent?

How to Combine Array Elements into a String in Java: A PHP join() Equivalent?

Published on 2024-10-31
Browse:490

 How to Combine Array Elements into a String in Java: A PHP join() Equivalent?

Java Functionality Similar to PHP's join() for Arrays

PHP's join() function is designed to concatenate elements of an array into a single string, separated by a specified glue string. Does Java offer a comparable functionality?

Java 8 and Beyond: Utilizing String.join()

Starting with Java 8, the String class introduced the join() method, providing a concise solution to this task. It accepts two arguments: the glue string and the array of elements to be joined. For instance:

String.join(", ", new String[]{"Hello", "World", "!"});

which would produce the following result:

Hello, World, !

Alternative Option: Apache Commons Lang's Join Function

For Java versions prior to 8 or in cases where Apache Commons Lang is already in use, the StringUtils class provides a join() function that can concatenate array elements as well. Here's an example:

StringUtils.join(new String[] {"Hello", "World", "!"}, ", ");

This code would generate the following String:

Hello, World, !
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3