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!