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

其他回答

你可以从Spring框架的StringUtils中使用它。我知道它已经被提到过,但是实际上您可以只使用这段代码,它就可以立即工作,而不需要Spring。

// from https://github.com/spring-projects/spring-framework/blob/master/spring-core/src/main/java/org/springframework/util/StringUtils.java

/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public class StringUtils {
    public static String collectionToDelimitedString(Collection<?> coll, String delim, String prefix, String suffix) {
        if(coll == null || coll.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        Iterator<?> it = coll.iterator();
        while (it.hasNext()) {
            sb.append(prefix).append(it.next()).append(suffix);
            if (it.hasNext()) {
                sb.append(delim);
            }
        }
        return sb.toString();
    }
}

如果您正在使用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类中提供了这样一个东西,以防您不想自己编写它。

谷歌的Guava API也有.join(),尽管(从其他回复中应该很明显),Apache Commons在这里几乎是标准的。

试试这个:

java.util.Arrays.toString(anArray).replaceAll(", ", ",")
                .replaceFirst("^\\[","").replaceFirst("\\]$","");