Home >Java >javaTutorial >How to Efficiently Create Comma-Delimited Strings in Java?
In Java, assembling a list of values into a delimited string is a common requirement. While basic approaches involve iterative concatenation, cleaner alternatives exist.
Pre-Java 8:
Leverage Apache's commons lang library, which provides a StringUtils.join() method analogous to Ruby's join.
Java 8 onwards:
StringJoiner:
String.join(delimiter, array):
String.join(delimiter, iterable):
Example:
// Using StringJoiner List<String> list = new ArrayList<>(); list.add("element1"); list.add("element2"); StringJoiner joiner = new StringJoiner(","); joiner.addAll(list); String delimitedString = joiner.toString(); // Using String.join(array) String[] elements = new String[] {"element1", "element2"}; String delimitedString = String.join(",", elements); // Using String.join(iterable) List<String> list2 = new ArrayList<>(); list2.add("element1"); list2.add("element2"); String delimitedString = String.join(",", list2);
These methods provide efficient and elegant solutions for creating delimited strings in Java, eliminating the need for multiple string creations and concatenation.
The above is the detailed content of How to Efficiently Create Comma-Delimited Strings in Java?. For more information, please follow other related articles on the PHP Chinese website!