java中将list用逗号隔开拼成字符串的四种方法

1 Stream流

public static String parseListToStr(List list){ String result = list.stream().map(String::valueOf).collect(Collectors.joining(",")); return result; }

2 使用谷歌Joiner方法

import com.google.common.base.Joiner; public static String parseListToStr1(List list){ String result = Joiner.on(",").join(list); return result; }

3 循环插入逗号

public static String parseListToStr2(List list) { StringBuffer sb=new StringBuffer(); if( listIsNotFull ( list ) ){ for(int i = 0; i < = list.size()-1;i++){ sb.append(list.get(i)+","); }else{ sb.append(list.get(i)); } } return sb.toString(); }

4 lambda表达式遍历并加入符号

public static String parseListToStr3(List list){ StringBuffer sb = new StringBuffer(); list.stream().forEach(str - > { sb .append(str). append(",");}); sb.deleteCharAt(sb.length()-1); return sb.toString(); }

5 org.apache.commons.lang.StringUtils lang包下面

public static String parseListToStr3(List list){ String str= StringUtils.join(list,","); return str; }
经验分享 程序员 微信小程序 职场和发展