JavaScript有Array.join()

js>["Bill","Bob","Steve"].join(" and ")
Bill and Bob and Steve

Java有这样的东西吗?我知道我可以用StringBuilder自己拼凑一些东西:

static public String join(List<String> list, String conjunction)
{
   StringBuilder sb = new StringBuilder();
   boolean first = true;
   for (String item : list)
   {
      if (first)
         first = false;
      else
         sb.append(conjunction);
      sb.append(item);
   }
   return sb.toString();
}

. .但是如果像这样的东西已经是JDK的一部分,那么这样做就没有意义了。


当前回答

不是开箱即用,但许多库都有类似的:

Commons Lang:

org.apache.commons.lang.StringUtils.join(list, conjunction);

春天:

org.springframework.util.StringUtils.collectionToDelimitedString(list, conjunction);

其他回答

所有对Apache Commons的引用都很好(这是大多数人使用的),但我认为与Guava相当的Joiner具有更好的API。

你可以使用简单的连接

Joiner.on(" and ").join(names)

但也很容易处理空值:

Joiner.on(" and ").skipNulls().join(names);

or

Joiner.on(" and ").useForNull("[unknown]").join(names);

和(就我而言,它比common -lang更有用),处理map的能力:

Map<String, Integer> ages = .....;
String foo = Joiner.on(", ").withKeyValueSeparator(" is ").join(ages);
// Outputs:
// Bill is 25, Joe is 30, Betty is 35

这对于调试等非常有用。

不,在标准Java API中没有这样方便的方法。

毫不奇怪,Apache Commons在它们的StringUtils类中提供了这样一个东西,以防您不想自己编写它。

你可能想试试Apache Commons StringUtils join方法:

以http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html加入(java.util.Iterator)

我发现Apache StringUtils捡起jdk的懈怠;-)

不是开箱即用,但许多库都有类似的:

Commons Lang:

org.apache.commons.lang.StringUtils.join(list, conjunction);

春天:

org.springframework.util.StringUtils.collectionToDelimitedString(list, conjunction);

EDIT

我还注意到toString()底层实现问题,以及包含分隔符的元素,但我认为我是偏执狂。

鉴于我对此有两点看法,我将我的答案改为:

static String join( List<String> list , String replacement  ) {
    StringBuilder b = new StringBuilder();
    for( String item: list ) { 
        b.append( replacement ).append( item );
    }
    return b.toString().substring( replacement.length() );
}

这看起来和最初的问题很相似。

所以如果你不想把整个罐子添加到你的项目中,你可以使用这个。

我认为你原来的代码没有问题。实际上,每个人都建议的替代方案看起来几乎相同(尽管它做了一些额外的验证)

这里有Apache 2.0许可证。

public static String join(Iterator iterator, String separator) {
    // handle null, zero and one elements before building a buffer
    if (iterator == null) {
        return null;
    }
    if (!iterator.hasNext()) {
        return EMPTY;
    }
    Object first = iterator.next();
    if (!iterator.hasNext()) {
        return ObjectUtils.toString(first);
    }

    // two or more elements
    StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
    if (first != null) {
        buf.append(first);
    }

    while (iterator.hasNext()) {
        if (separator != null) {
            buf.append(separator);
        }
        Object obj = iterator.next();
        if (obj != null) {
            buf.append(obj);
        }
    }
    return buf.toString();
}

现在我们知道了,谢谢开源