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


当前回答

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类可能也很有用。

其他回答

你可以这样做:

String aToString = java.util.Arrays.toString(anArray);
// Do not need to do this if you are OK with '[' and ']'
aToString = aToString.substring(1, aToString.length() - 1);

或者单行语句(仅当不需要'['和']'时)

String aToString = java.util.Arrays.toString(anArray).substring(1).replaceAll("\\]$", "");

希望这能有所帮助。

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

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 Commons StringUtils join方法:

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

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

使用java 8收集器,这可以用以下代码完成:

Arrays.asList("Bill", "Bob", "Steve").stream()
.collect(Collectors.joining(" and "));

此外,java 8中最简单的解决方案:

String.join(" and ", "Bill", "Bob", "Steve");

or

String.join(" and ", Arrays.asList("Bill", "Bob", "Steve"));

你可以从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();
    }
}