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


当前回答

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

其他回答

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

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

String.join

在Java 8中,你不需要任何第三方库就可以做到这一点。

如果你想加入一个字符串集合,你可以使用String.join()方法:

List<String> list = Arrays.asList("foo", "bar", "baz");
String joined = String.join(" and ", list); // "foo and bar and baz"

Collectors.joining

如果你有一个非String类型的Collection,你可以使用Stream API来连接Collector:

List<Person> list = Arrays.asList(
  new Person("John", "Smith"),
  new Person("Anna", "Martinez"),
  new Person("Paul", "Watson ")
);

String joinedFirstNames = list.stream()
  .map(Person::getFirstName)
  .collect(Collectors.joining(", ")); // "John, Anna, Paul"

StringJoiner类可能也很有用。

用java 1.8的流可以使用,

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

List<String> list = Arrays.asList("Bill","Bob","Steve").
String str = list.stream().collect(Collectors.joining(" and "));

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

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