Java List轉字串逗號隔開且帶單引號字串
阿新 • • 發佈:2019-02-15
寫這個方法背景在於,Mybatis傳IN引數
1.將List<String>集合 轉化為'1','2','3','4','5'
/** * 將List<String>集合 轉化為String * 如{"aaa","bbb"} To 'aaa','bbb' */ public static String convertListToString(List<String> strlist){ StringBuffer sb = new StringBuffer(); if(CollectionUtils.isNotEmpty(strlist)){ for (int i=0;i<strlist.size();i++) { if(i==0){ sb.append("'").append(strlist.get(i)).append("'"); }else{ sb.append(",").append("'").append(strlist.get(i)).append("'"); } } } return sb.toString(); }
2. 將"1,2,3,4,5..."這種形式的字串轉成"'1','2','3','4'..."這種形式
/*** * 將"1,2,3,4,5..."這種形式的字串轉成List<String> 集合 * @param strs * @return * */ public static List<String> converStringToList(String strs) { if (StringUtils.isNotBlank(strs)) { String[] idStrs = strs.trim().split(","); if (null != idStrs && idStrs.length > 0) { List<String> strsList = new ArrayList<String>(); for (String str : idStrs) { if (StringUtils.isNotBlank(str)) { strsList.add(str.trim()); } } if (strsList.size() > 0) { return strsList; } } } return null; }
3.將"1,2,3,4,5..."這種形式的字串轉成List<String> 集合
/** 將"1,2,3,4,5..."這種形式的字串轉成"'1','2','3','4'..."這種形式 @param strs @return */ public static String converString(String strs) { if (StringUtils.isNotBlank(strs)) { String[] idStrs = strs.trim().split(","); if (null != idStrs && idStrs.length > 0) { StringBuffer sbf = new StringBuffer(""); for (String str : idStrs) { if (StringUtils.isNotBlank(str)) { sbf.append("'").append(str.trim()).append("'").append(","); } } if (sbf.length() > 0) { sbf = sbf.deleteCharAt(sbf.length() - 1); return sbf.toString(); } } } return ""; }