在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"
< a href =https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...- = noreferrer> String.join(CharSequence分隔符,CharSequence ...元素))
String joinedString = String.join(" - ", "04", "05", "06"); // "04 - 05 - 06"
< a href =https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable- =noreferrer > String.join(CharSequence分隔符,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屋!