java拼接逗号的四种方式
1.使用String.join
List<String> list = new ArrayList<>(Arrays.asList("1","2","3","4","5")); String result = String.join(",",list); System.out.println(result);
2.使用stream
List<String> 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<String> 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);