Java:将List<String>转换为连接()d字符串

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

545315 次浏览

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

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

您可以使用具有StringUtils类和连接方法的apache共享库。

查看此链接:https://commons.apache.org/proper/commons-lang/javadocs/api.2.0/org/apache/commons/lang/StringUtils.html

请注意,上面的链接可能会随着时间的推移而过时,在这种情况下,您可以在网络上搜索“apache Commons StringUtils”,这应该可以让您找到最新的参考。

(引用自此线程) JavaC#String. Format()和String. Join()的等价物

你可以这样做:

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("\\]$", "");

Hope this helps.

您可能想尝试Apache Commons StringUtils连接方法:

http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#join(java.util.迭代器,java.lang.String)

我发现Apache StringUtils可以弥补jdk的松弛;-)

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

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

使用示例:

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

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

下议院:

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

弹簧:

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

Google的Guava API也有.加入(),尽管(其他回复应该很明显),Apache Commons几乎是这里的标准。

编辑

我还注意到toString()底层实现问题,以及包含分隔符的元素,但我认为我是偏执的。

既然我在这方面有两个评论,我将我的答案改为:

static String join( List<String> list , String replacement  ) {
StringBuilder b = new StringBuilder();
for( String item: list ) {
b.append( replacement ).append( item );
}
return b.toString().substring( replacement.length() );
}

这看起来和原来的问题很相似。

因此,如果您不想将整个jar添加到您的项目中,您可以使用它。

我认为你的原始代码没有任何问题。事实上,每个人都在建议的替代方案看起来几乎相同(尽管它做了许多额外的验证)

在这里,随着Apache 2.0许可证。

public static String join(Iterator iterator, String separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return EMPTY;
}
Object first = iterator.next();
if (!iterator.hasNext()) {
return ObjectUtils.toString(first);
}


// two or more elements
StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}


while (iterator.hasNext()) {
if (separator != null) {
buf.append(separator);
}
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}

现在我们知道了,谢谢开源

所有对Apache Commons的引用都很好(这是大多数人使用的),但我认为番石榴等效的Joiner具有更好的API。

您可以执行简单的连接案例

Joiner.on(" and ").join(names)

但也可以轻松处理null:

Joiner.on(" and ").skipNulls().join(names);

Joiner.on(" and ").useForNull("[unknown]").join(names);

和(有用的足够就我而言,使用它优先于公地-lang),处理地图的能力:

Map<String, Integer> ages = .....;
String foo = Joiner.on(", ").withKeyValueSeparator(" is ").join(ages);
// Outputs:
// Bill is 25, Joe is 30, Betty is 35

这对于调试等非常有用。

我写了这个(我将它用于bean并利用toString,所以不要写Collection<String>):

public static String join(Collection<?> col, String delim) {
StringBuilder sb = new StringBuilder();
Iterator<?> iter = col.iterator();
if (iter.hasNext())
sb.append(iter.next().toString());
while (iter.hasNext()) {
sb.append(delim);
sb.append(iter.next().toString());
}
return sb.toString();
}

但是JSP不支持Collection,所以对于TLD我写了:

public static String join(List<?> list, String delim) {
int len = list.size();
if (len == 0)
return "";
StringBuilder sb = new StringBuilder(list.get(0).toString());
for (int i = 1; i < len; i++) {
sb.append(delim);
sb.append(list.get(i).toString());
}
return sb.toString();
}

并放入.tld文件:

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
<function>
<name>join</name>
<function-class>com.core.util.ReportUtil</function-class>
<function-signature>java.lang.String join(java.util.List, java.lang.String)</function-signature>
</function>
</taglib>

并在JSP文件中使用它:

<%@taglib prefix="funnyFmt" uri="tag:com.core.util,2013:funnyFmt"%>
${funnyFmt:join(books, ", ")}

一个有趣的方式来做它与纯JDK,在一个职责线:

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


String joined = Arrays.toString(array).replaceAll(", ", join)
.replaceAll("(^\\[)|(\\]$)", "");


System.out.println(joined);

输出:

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


一个不太完美和不太有趣的方式!

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


for (int i = 0; i < array.length; i++) array[i] = array[i].replaceAll(", ", "~,~");
String joined = Arrays.toString(array).replaceAll(", ", join)
.replaceAll("(^\\[)|(\\]$)", "").replaceAll("~,~", ", ");


System.out.println(joined);

输出:

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

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

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和苹果][和~,~

试试这个:

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

如果您使用的是Eclipse集合(以前的GS系列),则可以使用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集合类型,那么您可以摆脱适配器。

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集合的提交者。

String.join

使用Java8,您可以在没有任何第三方库的情况下执行此操作。

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

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

Collectors.joining

如果您有一个集合具有除String之外的其他类型,您可以将Stream API与连接收集器一起使用:

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

Java8解决方案java.util.StringJoiner

Java8有一个StringJoiner类。但是你仍然需要写一些样板,因为它Java。

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

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

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

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

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

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

Java8的三种可能性:

List<String> list = Arrays.asList("Alice", "Bob", "Charlie")


String result = String.join(" and ", list);


result = list.stream().collect(Collectors.joining(" and "));


result = list.stream().reduce((t, u) -> t + " and " + u).orElse("");

android上,您可以使用文字工具类。

TextUtils.join(" and ", names);

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

Java8带来了

Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

方法,通过对空值使用prefix + suffix来实现空安全。

它可以通过以下方式使用:

String s = stringList.stream().collect(Collectors.joining(" and ", "prefix_", "_suffix"))

Collectors.joining(CharSequence delimiter)方法只是在内部调用joining(delimiter, "", "")

可以使用java 1.8 stream,

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

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

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