Home >Java >javaTutorial >How Can I Efficiently Join Strings with Delimiters in Java?

How Can I Efficiently Join Strings with Delimiters in Java?

DDD
DDDOriginal
2024-12-09 21:06:111003browse

How Can I Efficiently Join Strings with Delimiters in Java?

Delimiting Items Elegantly in Java

In scenarios where you need to concatenate numerous values with a delimiter while avoiding redundant string handling, Java offers several approaches:

Pre-Java 8:

Apache Commons Lang's StringUtils.join() method provides a concise and efficient solution:

String joinedString = StringUtils.join(Arrays.asList("elementName", "anotherElementName"), ",");

Java 8:

StringJoiner:

StringJoiner allows for incremental concatenation:

StringJoiner joiner = new StringJoiner(",");
joiner.add("01").add("02").add("03");
String joinedString = joiner.toString(); // "01,02,03"

String.join():

This method offers a more concise syntax:

String joinedString = String.join(" ", "04", "05", "06"); // "04 - 05 - 06"

For iterable elements:

List<String> strings = Arrays.asList("Java", "is", "cool");
String message = String.join(" ", strings); // "Java is cool"

By utilizing these techniques, you can seamlessly concatenate delimited items in Java, enhancing code clarity and efficiency.

The above is the detailed content of How Can I Efficiently Join Strings with Delimiters in Java?. 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