1. toString() 方法
List.toString()是最简单的,但它在开头和结尾添加方括号,每个字符串用逗号分隔符分隔。
缺点是我们不能用另一个分隔符替换逗号,也不能去掉方括号
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class ListToStringUsingToStringExample {
public static void main(String args) { List<String> list = Arrays.asList("One", "Two", "Three", "Four", "Five"); String stringFromList = list.toString(); System.out.println("String : "+stringFromList); } }
|
2. Java 8 String.join()
java 8 String添加了一个特殊的方法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
| public class ListToStringUsingString_JoinExample {
public static void main(String args) { List<String> list = Arrays.asList("One", "Two", "Three", "Four", "Five"); String stringFromList = String.join("~", list); System.out.println("String with tilde delimiter: "+stringFromList); String stringPipe = String.join("|", list); System.out.println("String with pipe delimiter : "+stringPipe); } }
|
3. Collectors.joining()
Collectors.join()方法来自 java 8 stream api。Collctors.joining()方法将分隔符、前缀和后缀作为参数。此方法将列表转换为具有给定分隔符、前缀和后缀的字符串。
查看以下有关使用不同分隔符的 join() 方法的示例。但是,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
| public class ListToStringUsingString_JoinExample {
public static void main(String args) { List<String> list = Arrays.asList("One", "Two", "Three", "Four", "Five"); String joiningString = list.stream().collect(Collectors.joining("-", "{", "}")); System.out.println("Collectors.joining string : "+joiningString); String joiningString3 = list.stream().collect(Collectors.joining("@", "", "")); System.out.println("Collectors.joining string with @ separator : "+joiningString3); } }
|
4. Apache Commons StringUtils.join()
使用来自 apache commons 包的外部库。该库有一个方法StringUtils.join() ,它采用类似于 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
| public class ListToStringUsingStringUtils_JoinExample {
public static void main(String args) { List<String> list = Arrays.asList("One", "Two", "Three", "Four", "Five"); String joiningString = StringUtils.join(list, "^"); System.out.println("StringUtils.join string with ^ delimiter : "+joiningString); String joiningString3 = StringUtils.join(list, "$"); System.out.println("StringUtils.join string with @ separator : "+joiningString3); } }
|