Comma separated String string - array - collection, mutual conversion

1. Prepare a comma separated string

String str = "小张,小王,小李,小赵";

2. Convert the comma-separated string to a set (it will be converted to an array before converting to a set)

// 第一种:先用split将字符串按逗号分割为数组,再用Arrays.asList将数组转换为集合
List<String> strList1 = Arrays.asList(str.split(","));
// 第二种:使用stream转换String集合
List<String> strList2 = Arrays.stream(str.split(",")).collect(Collectors.toList());
// 第三种:使用stream转换int集合(这种适用字符串是逗号分隔的类型为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. Convert collection to comma separated string

// 第一种:String.join(), JDK1.8+
str = String.join(",", strList1);
// 第二种:org.apache.commons.lang3.StringUtils. toArray():集合转换为数组
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)));
// 在上面已经处理为逗号拼接的字符串,下面为补充
// 在连接之前操作字符串, 拼接前缀和后缀
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. Convert array to comma separated string

String [] arr = (String[])strList1.toArray();
// 第一种:使用StringUtils的join方法
str = StringUtils.join(arr, ",");
// 第二种:使用ArrayUtils的toString方法,这种方式转换的字符串首尾加大括号 输出示例:{小张,小王,小李,小赵}
ArrayUtils.toString(arr, ",");

Guess you like

Origin blog.csdn.net/qq_25983579/article/details/132696108