• 逗号分隔String字符串 - 数组 - 集合,相互转换


    1. 准备一个逗号分割字符串

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

    2. 逗号分割字符串转换为集合(转换为集合之前会先转换为数组)

    // 第一种:先用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));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    3. 集合转换为逗号分隔的字符串

    // 第一种: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,",");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    4. 数组转逗号分隔字符串

    String [] arr = (String[])strList1.toArray();
    // 第一种:使用StringUtils的join方法
    str = StringUtils.join(arr, ",");
    // 第二种:使用ArrayUtils的toString方法,这种方式转换的字符串首尾加大括号 输出示例:{小张,小王,小李,小赵}
    ArrayUtils.toString(arr, ",");
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    vue3 html2canvas 网络图片 空白 及使用
    群辉NAS:ARPL引导黑群晖DSM 7.2详细教程
    从零开始搭建仿抖音短视频APP--开发用户业务模块(4)
    PHP 如何创建一个 composer 包 并在 项目中使用自己的 composer sdk 包
    A-Level经济真题
    Python老手也会犯的20个新手级错误
    SMOKE 单目相机 3D目标检测【训练模型】
    Python深度学习之路:TensorFlow与PyTorch对比【第140篇—Python实现】
    EcoVadis评估资讯-2024年公布的记分卡将受奖牌分数新规则约束
    layUI.open在手机端小屏幕不能显示全页面,也没办法滑动
  • 原文地址:https://blog.csdn.net/qq_25983579/article/details/132696108