1.使用谷歌的Joiner转换
1
2
3
4
|
public static <T> String parseListToStr(List<T> list){ String result = Joiner.on( "," ).join(list); return result; } |
2.使用lambda表达式遍历集合
1
2
3
4
5
6
7
8
|
public static <T> String parseListToStr2(List<T> list){ StringBuffer sb = new StringBuffer(); list.stream().forEach(str->{ sb.append(str).append( "," ); }); sb.deleteCharAt(sb.length()- 1 ); return sb.toString(); } |
3.直接使用stream流实现
1
2
3
4
|
public static <T> String parseListToStr3(List<T> list){ String result = list.stream().map(String::valueOf).collect(Collectors.joining( "," )); return result; } |
4.使用for循环遍历集合
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public static <T> String parseListToStr(List<T> list){ StringBuffer sb = new StringBuffer(); if (listIsNotNull(list)) { for ( int i= 0 ;i<=list.size()- 1 ;i++){ if (i<list.size()- 1 ){ sb.append(list.get(i) + "," ); } else { sb.append(list.get(i)); } } } return sb.toString(); } |
注意:在转换集合前应该都统一做判空处理
到此这篇关于Java8 将List转换为用逗号隔开的字符串的几种方法的文章就介绍到这了,更多相关Java8 List转字符串内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/londa/article/details/114807897