1.使用谷歌的Joiner转换 (引用guava包)
1 public static <T> String parseListToStr(List<T> list){
2 String result = Joiner.on(",").join(list);
3 return result;
4 }
2.使用lambda表达式遍历集合
1 public static <T> String parseListToStr2(List<T> list){
2 StringBuffer sb = new StringBuffer();
3 list.stream().forEach(str->{
4 sb.append(str).append(",");
5 });
6 sb.deleteCharAt(sb.length()-1);
7 return sb.toString();
8 }
3.直接使用stream流实现
1 public static <T> String parseListToStr3(List<T> list){
2 String result = list.stream().map(String::valueOf).collect(Collectors.joining(","));
3 return result;
4 }
4.使用for循环遍历集合
1 public static <T> String parseListToStr(List<T> list){
2 StringBuffer sb = new StringBuffer();
3 if(listIsNotNull(list)) {
4 for(int i=0;i<=list.size()-1;i++){
5 if(i<list.size()-1){
6 sb.append(list.get(i) + ",");
7 }else {
8 sb.append(list.get(i));
9 }
10 }
11 }
12 return sb.toString();
13 }
注意:在转换集合前应该都统一做判空处理
原文地址:https://www.cnblogs.com/raoyulu/p/13573612.html