Java:将 List<String> 转换为 String

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1751844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:18:20  来源:igfitidea点击:

Java: convert List<String> to a String

javalist

提问by Jason S

JavaScript has Array.join()

JavaScript 有 Array.join()

js>["Bill","Bob","Steve"].join(" and ")
Bill and Bob and Steve

Does Java have anything like this? I know I can cobble something up myself with StringBuilder:

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

...but there's no point in doing this if something like it is already part of the JDK.

...但是如果类似的东西已经是 JDK 的一部分,那么这样做就没有意义了。

采纳答案by micha

With Java 8 you can do this without any third party library.

使用 Java 8,您无需任何第三方库即可完成此操作。

If you want to join a Collection of Strings you can use the new String.join()method:

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

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

If you have a Collection with another type than String you can use the Stream API with the joining Collector:

如果您的 Collection 类型不是 String ,则可以将 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"

The StringJoinerclass may also be useful.

StringJoiner班也可能是有用的。

回答by Bart Kiers

No, there's no such convenience method in the standard Java API.

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

Not surprisingly, Apache Commons provides such a thing in their StringUtils classin case you don't want to write it yourself.

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

回答by dcp

You can use the apache commons library which has a StringUtils class and a join method.

您可以使用具有 StringUtils 类和 join 方法的 apache 公共库。

Check this link: https://commons.apache.org/proper/commons-lang/javadocs/api.2.0/org/apache/commons/lang/StringUtils.html

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

Note that the link above may become obsolete over time, in which case you can just search the web for "apache commons StringUtils", which should allow you to find the latest reference.

请注意,随着时间的推移,上面的链接可能会过时,在这种情况下,您只需在网络上搜索“apache commons StringUtils”,您就可以找到最新的参考资料。

(referenced from this thread) Java equivalents of C# String.Format() and String.Join()

(从此线程引用) C# String.Format() 和 String.Join() 的 Java 等效项

回答by NawaMan

You can do this:

你可以这样做:

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

Or a one-liner (only when you do not want '[' and ']')

或单行(仅当您不想要 '[' 和 ']' 时)

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

Hope this helps.

希望这可以帮助。

回答by Upgradingdave

You might want to try Apache Commons StringUtils join method:

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

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

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

I've found that Apache StringUtils picks up jdk's slack ;-)

我发现 Apache StringUtils 弥补了 jdk 的不足 ;-)

回答by Juha Syrj?l?

Code you have is right way to do it if you want to do using JDK without any external libraries. There is no simple "one-liner" that you could use in JDK.

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

If you can use external libs, I recommend that you look into org.apache.commons.lang.StringUtilsclass in Apache Commons library.

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

An example of usage:

用法示例:

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

回答by Arne Burmeister

Not out of the box, but many libraries have similar:

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

Commons Lang:

康斯朗:

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

Spring:

春天:

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

回答by Dean J

Google's Guava API also has .join(), although (as should be obvious with the other replies), Apache Commons is pretty much the standard here.

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

回答by OscarRyz

EDIT

编辑

I also notice the toString()underlying implementation issue, and about the element containing the separator but I thought I was being paranoid.

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

Since I've got two comments on that regard, I'm changing my answer to:

由于我在这方面有两个评论,我将我的答案更改为:

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

Which looks pretty similar to the original question.

这看起来与原始问题非常相似。

So if you don't feel like adding the whole jar to your project you may use this.

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

I think there's nothing wrong with your original code. Actually, the alternative that everyone's is suggesting looks almost the same ( although it does a number of additional validations )

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

Here it is, along with the Apache 2.0 license.

在这里,还有 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();
}

Now we know, thank you open source

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

回答by Cowan

All the references to Apache Commons are fine (and that is what most people use) but I think the Guavaequivalent, Joiner, has a much nicer API.

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

You can do the simple join case with

你可以做简单的连接案例

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

but also easily deal with nulls:

但也很容易处理空值:

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

or

或者

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

and (useful enough as far as I'm concerned to use it in preference to commons-lang), the ability to deal with Maps:

和(就我而言,它比 commons-lang 更有用),处理 Maps 的能力:

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

which is extremely useful for debugging etc.

这对于调试等非常有用。

回答by gavenkoa

I wrote this one (I use it for beans and exploit toString, so don't write Collection<String>):

我写了这个(我用它做 bean 和exploit 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();
}

but Collectionisn't supported by JSP, so for TLD I wrote:

Collection不受 JSP 支持,因此对于 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();
}

and put to .tldfile:

并放入.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>

and use it in JSP files as:

并在 JSP 文件中使用它作为:

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