在日常开发工作中,经常会遇到需要将 List<String> 转换为使用某个符号连接的字符串。如将 List<String> 转换为按英文逗号(,)分隔的字符串:

1
2
3
4
5
6
7
8
9
10
11
12
List<String> weekList = Arrays.asList(
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
);

// 将 weekList 输出转换为按英文逗号(,)分隔的字符串:
// Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday

最容易想到的拼接方式,是通过 for 循环来实现。不过,如果你使用 Java 8 或以上的版本进行开发,实现该功能将变得非常简单,通常有以下两种方法。

方法一:使用 String.join,主要代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 此代码示例演示 String.join 方法的使用

package com.jomoo;

import java.util.Arrays;
import java.util.List;

public class Application {
public static void main(String[] args) {
List<String> weekList = Arrays.asList(
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
);
System.out.println(String.join(",", weekList));
}
}

/*
此代码示例执行结果如下:

Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday

*/

方法二:采用流的方式(stream())来写,就像下面这样,仍然能够得到同样的结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 此代码示例演示流方式(stream)进行拼接

package com.jomoo;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Application {
public static void main(String[] args) {
List<String> weekList = Arrays.asList(
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
);

String str = weekList.stream().collect(Collectors.joining(","));
System.out.println(str);
}
}

/*
此代码示例执行结果如下:

Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
*/

此外,如果你想在连接成字符串之前,先对元素进行其他的操作,如过滤元素、转成大写等,采用流的方式实现也很方便。以下代码展示如何将整个字符串在连接之前先转为大写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 此代码示例演示在连接之前先将元素转为大写

package com.jomoo;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Application {
public static void main(String[] args) {
List<String> weekList = Arrays.asList(
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
);

String str = String str = weekList.stream()
.map(String::toUpperCase)
.collect(Collectors.joining(","));

System.out.println(str);
}
}

/*
此代码示例执行结果如下:

MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY
*/

(END)