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


当前回答

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

其他回答

如果你想在没有任何外部库的情况下使用JDK,那么你拥有的代码是正确的方法。在JDK中没有可以使用的简单的“一行程序”。

如果您可以使用外部库,我建议您查看Apache Commons库中的org.apache.commons.lang.StringUtils类。

用法示例:

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

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

Commons Lang:

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

春天:

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

实现它的一个正统方法是定义一个新函数:

public static String join(String joinStr, String... strings) {
    if (strings == null || strings.length == 0) {
        return "";
    } else if (strings.length == 1) {
        return strings[0];
    } else {
        StringBuilder sb = new StringBuilder(strings.length * 1 + strings[0].length());
        sb.append(strings[0]);
        for (int i = 1; i < strings.length; i++) {
            sb.append(joinStr).append(strings[i]);
        }
        return sb.toString();
    }
}

示例:

String[] array = new String[] { "7, 7, 7", "Bill", "Bob", "Steve",
        "[Bill]", "1,2,3", "Apple ][","~,~" };

String joined;
joined = join(" and ","7, 7, 7", "Bill", "Bob", "Steve", "[Bill]", "1,2,3", "Apple ][","~,~");
joined = join(" and ", array); // same result

System.out.println(joined);

输出:

7,7,7和比尔,鲍勃,史蒂夫和[比尔],1,2,3和苹果][和~,~

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

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

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

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

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