在 Java 中构建一串分隔项的最佳方法是什么? [英] What's the best way to build a string of delimited items in Java?
问题描述
在 Java 应用程序中工作时,我最近需要组装一个以逗号分隔的值列表,以传递给另一个 Web 服务,而无需事先知道有多少元素.我能想到的最好的事情是这样的:
While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this:
public String appendWithDelimiter( String original, String addition, String delimiter ) {
if ( original.equals( "" ) ) {
return addition;
} else {
return original + delimiter + addition;
}
}
String parameterString = "";
if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," );
if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );
我意识到这不是特别有效,因为到处都在创建字符串,但我更多的是为了清晰而不是优化.
I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization.
在 Ruby 中,我可以做这样的事情,感觉更优雅:
In Ruby, I can do something like this instead, which feels much more elegant:
parameterArray = [];
parameterArray << "elementName" if condition;
parameterArray << "anotherElementName" if anotherCondition;
parameterString = parameterArray.join(",");
但由于 Java 缺少连接命令,我无法找出任何等效的东西.
But since Java lacks a join command, I couldn't figure out anything equivalent.
那么,在 Java 中执行此操作的最佳方法是什么?
So, what's the best way to do this in Java?
推荐答案
Pre Java 8:
Apache 的 commons lang 是您的朋友 - 它提供了一种与您在 Ruby 中引用的非常相似的连接方法:
Pre Java 8:
Apache's commons lang is your friend here - it provides a join method very similar to the one you refer to in Ruby:
StringUtils.join(java.lang.Iterable,char)
Java 8 通过 StringJoiner
和 String.join()
提供开箱即用的连接.下面的片段展示了如何使用它们:
Java 8 provides joining out of the box via StringJoiner
and String.join()
. The snippets below show how you can use them:
StringJoiner joiner = new StringJoiner(",");
joiner.add("01").add("02").add("03");
String joinedString = joiner.toString(); // "01,02,03"
<小时>
String.join(CharSequence delimiter, CharSequence...元素))
String joinedString = String.join(" - ", "04", "05", "06"); // "04 - 05 - 06"
<小时>
String.join(CharSequence delimiter, Iterable extends CharSequence> 元素)
List<String> strings = new LinkedList<>();
strings.add("Java");strings.add("is");
strings.add("cool");
String message = String.join(" ", strings);
//message returned is: "Java is cool"
这篇关于在 Java 中构建一串分隔项的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!