java拼接逗号的四种方式

作者: adm 分类: java 发布时间: 2024-01-19

1.使用String.join
 
List list = new ArrayList<>(Arrays.asList("1","2","3","4","5"));
String result = String.join(",",list);
System.out.println(result);
 
2.使用stream
List list = new ArrayList<>(Arrays.asList("1","2","3","4","5"));
String result2 = list.stream().collect(Collectors.joining(","));
System.out.println(result2);
 
3.使用StringBuffer
StringBuffer sb = new StringBuffer();
for(String str : list){
    sb.append(str).append(",");
}
String result3 = sb.toString().substring(0,sb.length()-1);
System.out.println(result3);
 
4.使用for
List list = new ArrayList<>(Arrays.asList("1","2","3","4","5"));
String result4 = "";
for(int i = 0;i < list.size();i++){
    if(i == list.size() - 1){
        result4 += list.get(i);
    }else{
        result4 += list.get(i) + ",";
    }
}
System.out.println(result4);

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!