Java8-如何将List转变为逗号分隔的字符串

本文介绍如何在Java8中将列表转换为逗号分隔的字符串,并提供了使用String.join()和流API的示例代码。此外,还展示了如何在连接前对字符串进行操作,如转换为大写。
该文章已生成可运行项目,

Converting a List to a String with all the values of the List comma separated in Java 8 is really straightforward. Let’s have a look how to do that.

在Java 8中将集合List转变为用逗号分隔的String是非常简单的,下面让我看看如何做到

In Java 8

We can simply write String.join(..), pass a delimiter and an Iterable and the new StringJoiner will do the rest:

我们使用String.join()函数,给函数传递一个分隔符合一个迭代器,一个StringJoiner对象会帮助我们完成所有的事情

List<String> cities = Arrays.asList("Milan", 
                                    "London", 
                                    "New York", 
                                    "San Francisco");
String citiesCommaSeparated = String.join(",", cities);
System.out.println(citiesCommaSeparated);
//Output: Milan,London,New York,San Francisco

If we are working with stream we can write as follow and still have the same result:

如果我们采用流的方式来写,就像下面这样,仍然能够得到同样的结果

String citiesCommaSeparated = cities.stream()
                                    .collect(Collectors.joining(","));
System.out.println(citiesCommaSeparated);
//Output: Milan,London,New York,San Francisco
Note: you can statically import java.util.stream.Collectors.joining if you prefer just typing "joining".

In Java 7

For old times’ sake, let’s have a look at the Java 7 implementation:

由于老的缘故,让我们看看在java 7中如何实现这个功能

private static final String SEPARATOR = ",";
public static void main(String[] args) {
  List<String> cities = Arrays.asList(
                                "Milan", 
                                "London", 
                                "New York", 
                                "San Francisco");
  StringBuilder csvBuilder = new StringBuilder();
  for(String city : cities){
    csvBuilder.append(city);
    csvBuilder.append(SEPARATOR);
  }
  String csv = csvBuilder.toString();
  System.out.println(csv);
  //OUTPUT: Milan,London,New York,San Francisco,
  //Remove last comma
  csv = csv.substring(0, csv.length() - SEPARATOR.length());
  System.out.println(csv);
  //OUTPUT: Milan,London,New York,San Francisco
}

As you can see it’s much more verbose and easier to make mistakes like forgetting to remove the last comma. You can implement this in several ways—for example by moving the logic that removes the last comma to inside the for-loop—but no implementation will be so explicative and easy to understand as the declarative solution expressed in Java 8.

正如你所看到的,这种方式更加啰嗦并且更加容易犯诸如忘记去除最后一个逗号之类的错误。你能够采用几种方式来完成这一功能-例如你可以将删除最后一个逗号的操作逻辑放到for循环中,但是没有一种实现方式向java 8中如此可解释性并且容易理解

Focus should be on what you want to do—joining a List of String—not on how.

注意力应该放到你想做什么-连接List结合,而不是怎样做

Java 8: Manipulate String Before Joining

If you are using Stream, it’s really straightforward manipulate your String as you prefer by using map() or cutting some String out by using filter(). I’ll cover those topics in future articles. Meanwhile, this a straightforward example on how to transform the whole String to upper-case before joining.

Java 8: 在连接之前操作字符串

如果你使用流,使用map函数或者用于删掉一些字符串的filter函数能够更加直观的操作字符串。我在将来的文章中会覆盖这些主题。同时,这也是一个直观展示如何将整个字符串在连接之前转为大写的例子。

Java 8: From List to Upper-Case String Comma Separated

将List集合转为大写的用逗号分隔的String

String citiesCommaSeparated = cities.stream()
                                    .map(String::toUpperCase)
                                    .collect(Collectors.joining(","));
//Output: MILAN,LONDON,NEW YORK,SAN FRANCISCO
If you  want to find out more about stream, I strongly suggest this cool video from Venkat Subramaniam.

Let’s Play
The best way to learn is playing! Copy this class with all the implementations discussed and play with that. There is already a small test for each of them.

让我们尝试一下。最好的学习方式是动手尝试。复制下面讨论的全部实现的类并且运行它。其中对于每一个实现几乎都有一个小的测试。

package net.reversecoding.examples;
import static java.util.stream.Collectors.joining;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class CsvUtil {
private static final String SEPARATOR = ",";
public static String toCsv(List<String> listToConvert){
return String.join(SEPARATOR, listToConvert);
}
@Test
public void toCsv_csvFromListOfString(){
List<String> cities = Arrays.asList(
"Milan", "London", "New York", "San Francisco");
String expected = "Milan,London,New York,San Francisco";
assertEquals(expected, toCsv(cities));
}
public static String toCsvStream(List<String> listToConvert){
return listToConvert.stream()
.collect(joining(SEPARATOR));
}
@Test
public void toCsvStream_csvFromListOfString(){
List<String> cities = Arrays.asList(
"Milan", "London", "New York", "San Francisco");
String expected = "Milan,London,New York,San Francisco";
assertEquals(expected, toCsv(cities));
}
public static String toCsvJava7(List<String> listToConvert){
StringBuilder csvBuilder = new StringBuilder();
for(String s : listToConvert){
csvBuilder.append(s);
csvBuilder.append(SEPARATOR);
}
String csv = csvBuilder.toString();
//Remove last separator
if(csv.endsWith(SEPARATOR)){
csv = csv.substring(0, csv.length() - SEPARATOR.length());
}
return csv;
}
@Test
public void toCsvJava7_csvFromListOfString(){
List<String> cities = Arrays.asList(
"Milan", "London", "New York", "San Francisco");
String expected = "Milan,London,New York,San Francisco";
assertEquals(expected, toCsvJava7(cities));
}
public static String toUpperCaseCsv(List<String> listToConvert){
return listToConvert.stream()
.map(String::toUpperCase)
.collect(joining(SEPARATOR));
}
@Test
public void toUpperCaseCsv_upperCaseCsvFromListOfString(){
List<String> cities = Arrays.asList(
"Milan", "London", "New York", "San Francisco");
String expected = "MILAN,LONDON,NEW YORK,SAN FRANCISCO";
assertEquals(expected, toUpperCaseCsv(cities));
}
}
本文章已经生成可运行项目
<think>首先,用户的问题是:“我想将Java 8中的List集合转换为逗号分隔字符串 请问Java 8 List逗号分隔字符串的方法”。这是一个关于Java编程的具体问题。 根据系统级指令: - 所有行内数学表达式必须使用$...$格式,但这里没有数学表达式,所以不需要。 - 独立公式必须使用$$...$$格式并单独成段,同样不适用。 - LaTeX语法正确:不涉及LaTeX。 - 使用中文回答:整个回答必须用中文。 - 生成相关问题:在回答后生成相关问题。 - 回答中引用的段落末尾自然地添加引用标识:参考提供的引用内容,我需要添加引用标识。 用户可见层指令: - 回答结构清晰,帮助用户逐步解决问题。 - 保证回答真实可靠。 参考提供的引用: - [^1]:使用Java 8Stream流,通过Collectors.joining(",")将List转换为逗号分隔字符串- [^2]:将逗号分隔字符串转换为List,使用Arrays.asList(str.split(","))。 - [^3]:Java8逗号分隔字符串转列表及列表转逗号分隔字符串操作,提到split()和Stream.of()。 - [^4]:一个自定义方法listToString,使用StringBuffer拼接字符串- [^5]:类似[^1]和[^2],提到使用StringBuilder和Java 8Stream。 用户的问题焦点是List逗号分隔字符串,所以我会主要参考[^1]和[^5]。 核心方法: - 使用Java 8Stream API:list.stream().collect(Collectors.joining(","))。这是最简洁和推荐的方式。 其他方法: - 传统方法:使用StringBuilder或StringBuffer手动拼接。 - 但用户指定了Java 8,所以Stream方法是首选。 回答结构: 1. **介绍问题**:简要说明需求。 2. **推荐方法**:使用Java 8Stream API。 - 提供代码示例。 3. **解释代码**:解释代码如何工作。 4. **其他方法**:简要提及其他方式,如自定义方法或StringBuilder,但强调Stream的优越性。 5. **添加引用**:在相关部分末尾添加引用标识。 6. **生成相关问题**:在最后添加相关问题。 生成相关问题: - 基于主题,如反向操作(字符串List)、性能考虑、错误处理等。 确保回答真实可靠: - 我熟悉Java编程,所以基于知识提供准确信息。 - 引用提供的参考内容来支持。 完整回答框架: - 开头:直接回答问题。 - 主体:分步骤解释。 - 结尾:生成相关问题。</think>### Java 8 List逗号分隔字符串的方法 在Java 8中,将List集合转换为逗号分隔字符串是一个常见需求,特别适合使用Stream API来实现。这种方法简洁高效,代码可读性强。下面我将逐步解释推荐方法,并提供代码示例。 #### 推荐方法:使用Stream API和Collectors.joining() Java 8引入了Stream API,其中`Collectors.joining()`方法专门用于将元素连接成字符串。以下是具体步骤和代码: 1. **导入必要包**:确保导入`java.util.stream.Collectors`。 2. **创建List**:定义一个List集合。 3. **转换为字符串**:调用`stream().collect(Collectors.joining(","))`,其中逗号作为分隔符。 示例代码: ```java import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class ListToStringExample { public static void main(String[] args) { // 创建一个List集合 List<String> list = Arrays.asList("a", "b", "c", "d"); // 使用Stream API转换为逗号分隔字符串 String result = list.stream() .collect(Collectors.joining(",")); System.out.println(result); // 输出: a,b,c,d } } ``` - **工作原理**: - `list.stream()`:将List转换为Stream流。 - `collect(Collectors.joining(","))`:使用`joining()`方法将所有元素连接起来,逗号作为分隔符。 - 这种方法处理空值或特殊字符时更安全,且性能高效[^1]。 #### 其他方法(可选,但不推荐) 虽然Stream API是首选,但Java 8也支持传统方式: - **使用StringBuilder手动拼接**:适合旧代码或简单场景,但代码冗长。 ```java StringBuilder sb = new StringBuilder(); for (String item : list) { if (sb.length() > 0) { sb.append(","); } sb.append(item); } String result = sb.toString(); // 输出相同 ``` - 注意:此方法需要手动处理分隔符,容易出错[^5]。 - **自定义工具方法**:参考引用中的`listToString`方法,但不如Stream简洁[^4]。 #### 为什么推荐Stream API? - **简洁性**:一行代码即可完成,减少错误。 - **性能**:`Collectors.joining()`在底层优化了字符串拼接,避免了不必要的对象创建[^1][^5]。 - **兼容性**:适用于Java 8及以上版本,符合现代编程习惯。 如果需要处理空列表或特殊字符,可以在`joining()`前添加`filter()`进行过滤。例如: ```java String result = list.stream() .filter(s -> s != null && !s.isEmpty()) // 过滤空值 .collect(Collectors.joining(",")); ``` ### 相关问题 1. 如何将逗号分隔字符串转换回Java List集合? 2. Java 8Stream API的性能如何优化? 3. 如何处理List中包含空值或特殊字符时的字符串转换? 4. Java中还有其他集合转字符串的简便方法吗?
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值