Convert a List to a Comma-Separated String – 将列表转换为逗号分隔的字符串

最后修改: 2022年 9月 30日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

List conversion is still a hot topic as it’s something that we do very often as Java developers. In this tutorial, we’ll learn how to convert a List of String to a comma-separated String using four different approaches.

List转换仍然是一个热门话题,因为这是我们作为 Java 开发人员非常经常做的事情。在本教程中,我们将学习如何使用四种不同的方法将ListString转换成逗号分隔的String

2. Using Java 8+

2.使用Java 8+

We’ll use three different classes and their methods, available since Java 8, for conversion.

我们将使用三个不同的类和它们的方法来进行转换,这些方法从Java 8开始就可用。

Let’s take the following list as input for the upcoming examples:

让我们把下面的列表作为接下来的例子的输入。

List<String> arraysAsList = Arrays.asList("ONE", "TWO", "THREE");

2.1. String

2.1.字符串

First, we’ll use the String class, which has many utilities for String processing and provides the conversion method join():

首先,我们将使用String类,它有许多处理String的实用程序,并提供了转换方法join()

String commaSeparatedString = String.join(",", arraysAsList);

assertThat(commaSeparatedString).isEqualTo("ONE,TWO,THREE");

2.2. StringJoiner

2.2.StringJoiner

Second, we’ll use the StringJoiner class, which has a constructor that accepts a CharSequence delimiter as a parameter:

其次,我们将使用StringJoiner类,它有一个构造函数,接受一个CharSequence分隔符作为参数:

StringJoiner stringJoiner = new StringJoiner(",");
arraysAsList.forEach(stringJoiner::add);
String commaSeparatedString = stringJoiner.toString();

assertThat(commaSeparatedString).isEqualTo("ONE,TWO,THREE");

There’s another constructor which takes a CharSequence delimiter, a CharSequence as a prefix, and another as a suffix:

还有一个构造函数,它需要一个CharSequence分隔符,一个CharSequence作为前缀,另一个作为后缀:

StringJoiner stringJoinerWithDelimiterPrefixSuffix = new StringJoiner(",", "[", "]");
arraysAsList.forEach(stringJoinerWithDelimiterPrefixSuffix::add);
String commaSeparatedStringWithDelimiterPrefixSuffix = stringJoinerWithDelimiterPrefixSuffix.toString();

assertThat(commaSeparatedStringWithDelimiterPrefixSuffix).isEqualTo("[ONE,TWO,THREE]");

2.3. Collectors

2.3.收集器

Third, the Collectors class provides various utility and joining() methods with different signatures.

第三,Collectors类提供了各种具有不同签名的效用和joining()方法。

Firstly let’s have a look at how to apply to a Stream the collect() method by using the Collectors.joining() method, which takes as input a CharSequence delimiter:

首先让我们看看如何通过使用Collectors.join()方法,将Stream应用于collect()方法,该方法将一个CharSequence分隔符作为输入。

String commaSeparatedUsingCollect = arraysAsList.stream()
  .collect(Collectors.joining(","));

assertThat(commaSeparatedUsingCollect).isEqualTo("ONE,TWO,THREE");

In our next example, we’ll see how to use the map() method to convert each object of the list into a String and then apply the methods collect() and Collectors.joining():

在下一个例子中,我们将看到如何使用map()方法将列表中的每个对象转换为String,然后应用collect()Collectors.joining()方法。

String commaSeparatedObjectToString = arraysAsList.stream()
  .map(Object::toString)
  .collect(Collectors.joining(","));

assertThat(commaSeparatedObjectToString).isEqualTo("ONE,TWO,THREE");

Next, we’ll use the map() method to convert the list elements into a String and then apply the methods collect() and Collectors.joining():

接下来,我们将使用map()方法将列表元素转换成String,然后应用collect()Collectors.join()方法。

String commaSeparatedStringValueOf = arraysAsList.stream()
  .map(String::valueOf)
  .collect(Collectors.joining(","));

assertThat(commaSeparatedStringValueOf).isEqualTo("ONE,TWO,THREE");

Now, let’s use map() as above, then the Collectors.joining() method that inputs a CharSequence delimiter, a CharSequence as a prefix, and a CharSequence as a suffix:

现在,让我们像上面那样使用map(),然后使用Collectors.joining()方法,输入一个CharSequence分隔符,一个CharSequence作为前缀,和一个CharSequence作为后缀。

String commaSeparatedStringValueOfWithDelimiterPrefixSuffix = arraysAsList.stream()
  .map(String::valueOf)
  .collect(Collectors.joining(",", "[", "]"));

assertThat(commaSeparatedStringValueOfWithDelimiterPrefixSuffix).isEqualTo("[ONE,TWO,THREE]");

Lastly, we’ll see how to use the reduce() method to convert the list instead of the collect():

最后,我们将看到如何使用reduce()方法来转换列表,而不是使用collect()

String commaSeparatedUsingReduce = arraysAsList.stream()
  .reduce((x, y) -> x + "," + y)
  .get();

assertThat(commaSeparatedUsingReduce).isEqualTo("ONE,TWO,THREE");

3. Using Apache Commons Lang

3.使用Apache Commons Lang

Alternatively, we can also use the utility classes provided by the Apache Commons Lang library instead of the Java ones.

另外,我们也可以使用Apache Commons Lang库提供的实用类,而不是Java的。

We must add a dependency to our pom.xml file to use Apache’s StringUtils class:

我们必须在我们的pom.xml文件中添加一个依赖,以使用Apache的StringUtils类:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.0</version>
</dependency>

The join() method has various implementations that accept inputs like a series of elements, an Iterator of values, also a delimiter under multiple forms such as String or char:

join()方法有多种实现方式,可以接受一系列元素、数值的Iterator等输入,也可以接受Stringchar等多种形式下的分隔符:

String commaSeparatedString = StringUtils.join(arraysAsList, ",");

assertThat(commaSeparatedString).isEqualTo("ONE,TWO,THREE");

If the information passed to join() is an array of Object, it also takes an int as startIndex and an int as endIndex:

如果传递给join()的信息是一个Object数组,它也需要一个int作为startIndex和一个int作为endIndex:

String commaSeparatedStringIndex = StringUtils.join(arraysAsList.toArray(), ",", 0, 3);

assertThat(commaSeparatedStringIndex).isEqualTo("ONE,TWO,THREE");

4. Using Spring Core

4.使用Spring Core

Spring Core library similarly provides a utility class having methods for this type of conversion.

Spring Core库同样提供了一个实用类,该类有用于这种类型转换的方法。

We first add a dependency to our pom.xml file to use Spring’s Core StringUtils class:

我们首先在我们的pom.xml文件中添加一个依赖,以使用Spring的核心StringUtils类:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.3.22</version>
</dependency>

Spring’s Core StringUtils class provides a method, collectionToCommaDelimitedString(), which takes a comma as the default delimiter and a Collection to convert as a parameter:

Spring的核心StringUtils类提供了一个方法,collectionToCommaDelimitedString(),该方法将逗号作为默认分隔符,并将一个Collection作为参数进行转换。

String collectionToCommaDelimitedString = StringUtils.collectionToCommaDelimitedString(arraysAsList);

assertThat(collectionToCommaDelimitedString).isEqualTo("ONE,TWO,THREE");

A second method, collectionToDelimitedString(), takes as parameters a Collection to convert and a String delimiter:

第二个方法,collectionToDelimitedString(),将一个要转换的Collection和一个Stringdelimiter作为参数:

String collectionToDelimitedString = StringUtils.collectionToDelimitedString(arraysAsList, ",");

assertThat(collectionToDelimitedString).isEqualTo("ONE,TWO,THREE");

5. Using Google Guava

5.使用Google Guava

Lastly, we’ll use the Google Guava library.

最后,我们将使用谷歌的Guava库。

We must add a dependency to our pom.xml file to use Google’s Guava Joiner class:

我们必须在我们的pom.xml文件中添加一个依赖,以使用Google的GuavaJoiner类:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.1-jre</version>
</dependency>

Google’s Guava Joiner class provides various methods we can apply consequently.

Google的Guava Joiner 类提供了各种我们可以随之应用的方法。

The first method is on(), which takes as a delimiter parameter a String, and then the second method is the join() method which takes as a parameter the Iterable having the values to convert:

第一个方法是on(),,它以String作为分隔符参数,然后第二个方法是join()方法,它以Iterable作为参数,具有要转换的值:

String commaSeparatedString = Joiner.on(",")
  .join(arraysAsList);

assertThat(commaSeparatedString).isEqualTo("ONE,TWO,THREE");

Let’s take another list containing some null values for the next example:

让我们拿另一个包含一些null值的列表作为下一个例子。

List<String> arraysAsListWithNull = Arrays.asList("ONE", null, "TWO", null, "THREE");

Given that, we can use other methods between the on() and join(), and one of these is the skipNulls() method. We can use it to avoid the conversion of the null values from inside the Iterable:

鉴于此,我们可以在on()join()之间使用其他方法,其中之一就是skipNulls()方法。我们可以用它来避免从Iterable内部转换null值:

String commaSeparatedStringSkipNulls = Joiner.on(",")
  .skipNulls()
  .join(arraysAsListWithNull);

assertThat(commaSeparatedStringSkipNulls).isEqualTo("ONE,TWO,THREE");

Another option is to use useForNull(), which takes a String value as a parameter to substitute the null values inside the Iterable to convert:

另一个选择是使用useForNull(),,它需要一个String值作为参数来替换Iterable里面的null值来进行转换:

String commaSeparatedStringUseForNull = Joiner.on(",")
  .useForNull(" ")
  .join(arraysAsListWithNull);

assertThat(commaSeparatedStringUseForNull).isEqualTo("ONE, ,TWO, ,THREE");

6. Conclusion

6.结论

In this article, we’ve seen various examples of converting a List of String to a comma-separated String. Finally, it’s up to us to choose which library and utility classes fit better for our purpose.

在这篇文章中,我们已经看到了将ListString转换为逗号分隔的String的各种例子。最后,由我们来选择哪个库和实用类更适合我们的目的。

As always, the complete code samples for this article can be found over on GitHub.

一如既往,本文的完整代码样本可以在GitHub上找到