在Java中构建分隔项字符串的最佳方法是什么?在Java应用程序中工作时,我最近需要组装一个以逗号分隔的值列表,以传递给另一个Web服务,而不知道预先会有多少元素。我能想到的最好的办法是: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", "," );我意识到这并不是特别有效,因为到处都在创建字符串,但我追求的是清晰而不是优化。在Ruby中,我可以这样做,这感觉更优雅:parameterArray = [];parameterArray << "elementName" if condition;parameterArray << "anotherElementName" if anotherCondition;parameterString = parameterArray.join(",");但是因为Java缺少一个JOIN命令,所以我找不到任何类似的东西。那么,用Java做这件事最好的方法是什么呢?
3 回答
红糖糍粑
TA贡献1815条经验 获得超6个赞
预Java 8:
StringUtils.join(java.lang.Iterable,char)
Java 8:
StringJoiner
String.join()
StringJoiner joiner = new StringJoiner(",");joiner.add("01").add("02").add("03");String joinedString = joiner.toString(); // "01,02,03"
String.join(CharSequence delimiter, CharSequence... elements))
String joinedString = String.join(" - ", "04", "05", "06"); // "04 - 05 - 06"
String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
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"
慕仙森
TA贡献1827条经验 获得超8个赞
public static String join(List<String> list, String delim) { StringBuilder sb = new StringBuilder(); String loopDelim = ""; for(String s : list) { sb.append(loopDelim); sb.append(s); loopDelim = delim; } return sb.toString();}
List<String> list = new ArrayList<String>(); if( condition ) list.add("elementName"); if( anotherCondition ) list.add("anotherElementName"); join(list, ",");
慕斯709654
TA贡献1840条经验 获得超5个赞
"My pets are: " + Joiner.on(", ").join(Arrays.asList("rabbit", "parrot", "dog")); // returns "My pets are: rabbit, parrot, dog"Joine r.on(" AND ").join(Arrays.asList("field1=1" , "field2=2", "field3=3"));// returns "field1=1 AND field2=2 AND field3=3"Joiner.on(",").ski pNulls().join(Arrays.asList("London", "Moscow", null, "New York", null, "Paris"));// returns "London,Moscow,New York,Paris"Joiner.on(", "). useForNull("Team held a draw").join(Arrays.asList("FC Barcelona", "FC Bayern", null, null, "Chelsea FC", "AC Milan"));// returns "FC Barcel ona, FC Bayern, Team held a draw, Team held a draw, Chelsea FC, AC Milan"
添加回答
举报
0/150
提交
取消