1. 程式人生 > 其它 >java將list轉為逗號隔開字串

java將list轉為逗號隔開字串

1.只要不為空,就在後面新增逗號,最後再用subString()函式擷取,去掉最後一位的逗號
List<String> test = new ArrayList<>();
String testStrings = "";
test.add("test1");
test.add("test2");
test.add("test3");

for(String object : test){
  if(object != null){
    testStrings +=object + ",";    
  }
}
if(testStrings.length > 0){
  testStrings = testStrings.substring(0,testStrings.length() -1);
}
2.通過StringUtils的join函式直接獲取逗號隔開字串
List<String> test = new ArrayList<>();
String testStrings = "";
test.add("test1");
test.add("test2");
test.add("test3");

String join = StringUtils.join(test,",");
System.out.println(join);
3.通過流轉換
String newStr = exList.stream().collect(Collectors.joining(",")))
4.將逗號連線的字串轉成字元陣列:
通過String的split函式可以實現

String aaa = "aa,bb,cc";
String[] split = aaa.split(",");

擇善人而交,擇善書而讀,擇善言而聽,擇善行而從。