Home > Java > javaTutorial > How Can I Efficiently Create Comma-Delimited String Lists in Java?

How Can I Efficiently Create Comma-Delimited String Lists in Java?

Mary-Kate Olsen
Release: 2024-12-29 10:24:11
Original
650 people have browsed it

How Can I Efficiently Create Comma-Delimited String Lists in Java?

Building Delimited String Lists in Java

You recently encountered a scenario in your Java application where you needed to create a comma-delimited list of values. While you came up with a rudimentary solution, it was inefficient due to the constant creation of strings. Inspired by Ruby's elegant join command, you sought an equivalent approach in Java.

Pre Java 8

Apache's commons lang library offers a StringUtils.join(java.lang.Iterable,char) method that mimics Ruby's join. This method efficiently joins an iterable of strings using the specified delimiter.

Java 8

Java 8 introduced built-in joining methods:

StringJoiner

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

String.join(CharSequence delimiter, CharSequence... elements)

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

String.join(CharSequence delimiter, Iterable elements)

<br>List<String> strings = new LinkedList<>();<br>strings.add("Java"); strings.add("is");<br>strings.add("cool");<br>String message = String.join(" ", strings);<br>//message returned is: "Java is cool"<br>

These methods provide efficient and elegant ways to build delimited string lists in Java, mimicking the functionality you enjoyed in Ruby.

The above is the detailed content of How Can I Efficiently Create Comma-Delimited String Lists in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template