在java开发中,有很多时候,需要把一个集合或者数组中的数据进行拼接,拼接成一个全新格式的字符串,这时候就用到了java中的一些方法,方法如下:
一、Joiner-guava
点击查看代码
//单个拼接
System.out.println(Joiner.on(",").join(1, 2));//1,2
//数组拼接
List<String> listStr = Arrays.asList("hello","java");
System.out.println(Joiner.on(",").join(listStr));//hello,java
List<Integer> list1 = Arrays.asList(1, 2, 5);
System.out.println(Joiner.on(",").join(list1));//1,2,5
二、String-java8
点击查看代码
//单个拼接
System.out.println(String.join(",", "1", "2"));//1,2
//字符串数组
String []list ={"hello","java"};
System.out.println(String.join(",",list));//hello,java
三、StringUtils.join
点击查看代码
String []list ={"hello","java"};
System.out.println(StringUtils.join(list,","));//hello,java
四、Stream流合并字符串、拼接字符串
点击查看代码
List<String> strings = Arrays.asList("abc", "", "de", "efg", "abcd", "", "jkl");
String mergeString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(","));
System.err.println("合并字符串 : "+mergeString);