1. 準(zhǔn)備一個(gè)逗號(hào)分割字符串
String str = "小張,小王,小李,小趙";
2. 逗號(hào)分割字符串轉(zhuǎn)換為集合(轉(zhuǎn)換為集合之前會(huì)先轉(zhuǎn)換為數(shù)組)
// 第一種:先用split將字符串按逗號(hào)分割為數(shù)組,再用Arrays.asList將數(shù)組轉(zhuǎn)換為集合
List<String> strList1 = Arrays.asList(str.split(","));
// 第二種:使用stream轉(zhuǎn)換String集合
List<String> strList2 = Arrays.stream(str.split(",")).collect(Collectors.toList());
// 第三種:使用stream轉(zhuǎn)換int集合(這種適用字符串是逗號(hào)分隔的類型為int類型)
List<Integer> intList = Arrays.stream(str.split(",")).map(Integer::parseInt).collect(Collectors.toList());
// 第四種:使用Guava的SplitterString
List<String> strList3= Splitter.on(",").trimResults().splitToList(str);
// 第五種:使用Apache Commons的StringUtils(只用到了他的split)
List<String> strList4= Arrays.asList(StringUtils.split(str,","));
// 第六種:使用Spring Framework的StringUtils
List<String> strList5 =Arrays.asList(StringUtils.commaDelimitedListToStringArray(str));
3. 集合轉(zhuǎn)換為逗號(hào)分隔的字符串
// 第一種:String.join(), JDK1.8+
str = String.join(",", strList1);
// 第二種:org.apache.commons.lang3.StringUtils. toArray():集合轉(zhuǎn)換為數(shù)組
str = StringUtils.join(strList1.toArray(), ",");
// 第三種:需要引入hutool工具包
str = Joiner.on(",").join(strList1);
// 第四種:StringJoiner, JDK1.8+ 輸出示例:START_小張,小王,小李,小趙_END
StringJoiner sj = new StringJoiner(",");
strList1.forEach(e -> sj.add(String.valueOf(e)));
// 在上面已經(jīng)處理為逗號(hào)拼接的字符串,下面為補(bǔ)充
// 在連接之前操作字符串, 拼接前綴和后綴
StringJoiner sj2 = new StringJoiner(",", "START_", "_END");
strList1.forEach(e -> sj2.add(String.valueOf(e)));
// 第五種:Stream, Collectors.joining(), JDK1.8+
str = strList1.stream().collect(Collectors.joining(","));
// 在連接之前操作字符串, 拼接前綴和后綴. 輸出示例:START_小張,小王,小李,小趙_END
str = strList1.stream().map(e -> {
if (e != null) return e.toUpperCase();
else return "null";
}).collect(Collectors.joining(",", "START_", "_END"));
// 第六種:使用Spring Framework的StringUtils
str = StringUtils.collectionToDelimitedString(strList1,",");
4. 數(shù)組轉(zhuǎn)逗號(hào)分隔字符串
String [] arr = (String[])strList1.toArray();
// 第一種:使用StringUtils的join方法
str = StringUtils.join(arr, ",");
// 第二種:使用ArrayUtils的toString方法,這種方式轉(zhuǎn)換的字符串首尾加大括號(hào) 輸出示例:{小張,小王,小李,小趙}
ArrayUtils.toString(arr, ",");
文章來源地址http://www.zghlxwxcb.cn/news/detail-759405.html
文章來源:http://www.zghlxwxcb.cn/news/detail-759405.html
到了這里,關(guān)于#java 逗號(hào)分隔String字符串 - 數(shù)組 - 集合,相互轉(zhuǎn)換的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!