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);

其他回答

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

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

如果您正在使用Eclipse Collections(以前的GS Collections),则可以使用makeString()方法。

List<String> list = Arrays.asList("Bill", "Bob", "Steve");

String string = ListAdapter.adapt(list).makeString(" and ");

Assert.assertEquals("Bill and Bob and Steve", string);

如果您可以将List转换为Eclipse Collections类型,那么您就可以摆脱适配器。

MutableList<String> list = Lists.mutable.with("Bill", "Bob", "Steve");
String string = list.makeString(" and ");

如果您只想要一个逗号分隔的字符串,您可以使用不接受参数的makeString()版本。

Assert.assertEquals(
    "Bill, Bob, Steve", 
    Lists.mutable.with("Bill", "Bob", "Steve").makeString());

注意:我是Eclipse Collections的提交者。

另一个解,它是另一个答案的变体

public static String concatStringsWSep(Iterable<String> strings, String separator) {
    Iterator<String> it = strings.iterator();
    if( !it.hasNext() ) return "";
    StringBuilder sb = new StringBuilder(it.next());
    while( it.hasNext()) {
        sb.append(separator).append(it.next());
    }
    return sb.toString();                           
}

你可以使用apache公共库,它有一个StringUtils类和一个join方法。

查看这个链接:https://commons.apache.org/proper/commons-lang/javadocs/api.2.0/org/apache/commons/lang/StringUtils.html

请注意,上面的链接可能会随着时间的推移而过时,在这种情况下,你可以在网上搜索“apache commons StringUtils”,它应该可以让你找到最新的引用。

(从这个线程引用) Java等价的c# String.Format()和String.Join()

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

Commons Lang:

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

春天:

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