在日常开发工作中,经常会遇到需要将 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" );
|
最容易想到的拼接方式,是通过 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
|
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)); } }
|
方法二:采用流的方式(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
|
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); } }
|
此外,如果你想在连接成字符串之前,先对元素进行其他的操作,如过滤元素、转成大写等,采用流的方式实现也很方便。以下代码展示如何将整个字符串在连接之前先转为大写:
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); } }
|
(END)