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的一部分,那么这样做就没有意义了。


当前回答

所有对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

这对于调试等非常有用。

其他回答

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

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

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

使用Java .util. stringjoiner的Java 8解决方案

Java 8有一个StringJoiner类。但您仍然需要编写一些样板文件,因为它是Java。

StringJoiner sj = new StringJoiner(" and ", "" , "");
String[] names = {"Bill", "Bob", "Steve"};
for (String name : names) {
   sj.add(name);
}
System.out.println(sj);

如果您正在使用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的提交者。

你可以使用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()

所有对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

这对于调试等非常有用。