java list逗号拼接字符串
志鸿鸣 人气:0第一种:使用谷歌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(); }
加载全部内容