java中 是什么分割的作用,在Java中构建一系列分隔项的最佳方法是什么?

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.

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(",");

But since Java lacks a join command, I couldn't figure out anything equivalent.

So, what's the best way to do this in Java?

解决方案

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:

Java 8:

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 joinedString = String.join(" - ", "04", "05", "06"); // "04 - 05 - 06"

List strings = new LinkedList<>();

strings.add("Java");strings.add("is");

strings.add("cool");

String message = String.join(" ", strings);

//message returned is: "Java is cool"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值