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.
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 introduced built-in joining methods:
<br>StringJoiner joiner = new StringJoiner(",");<br>joiner.add("01").add("02").add("03");<br>String joinedString = joiner.toString(); // "01,02,03"<br>
<br>String joinedString = String.join(" - ", "04", "05", "06"); // "04 - 05 - 06"<br>
<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!