时间:2022-10-25 09:32:59 | 栏目:JAVA代码 | 点击:次
第一种:使用谷歌Joiner方法
import com.google.common.base.Joiner; public static <T> String parseListToStr(List<T> list){ String result = Joiner.on(",").join(list); return result; }
第二种:循环插入逗号
//java项目www.fhadmin.org 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(); }
第三种:stream流
public static <T> String parseListToStr3(List<T> list){ String result = list.stream().map(String::valueOf).collect(Collectors.joining(",")); return result; }
第四种:lambda表达式遍历并加入逗号
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(); }