当前位置: 首页 > news >正文

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

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

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

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));

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,",");

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

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

相关文章:

  • 基于blockqueue的生产和消费模型
  • Editors(Vim)
  • 【Leetcode】134.加油站
  • 设计模式-建造者(生成器)模式
  • 内存泄露排查思路
  • kafka学习-概念与简单实战
  • 爬虫进阶-反爬破解5(selenium的优势和点击操作+chrome的远程调试能力+通过Chrome隔离实现一台电脑登陆多个账号)
  • 音视频编码格式-AAC ADT
  • 【计算机网络】网络编程接口 Socket API 解读(3)
  • kafka知识小结
  • 算法刷题记录-DP(LeetCode)
  • Springboot整合Neo4J图数据库
  • Unity 2018发布在iOS 16.3偶尔出现画面不动的问题
  • 蠕虫病毒流量分析案例
  • Transformer(一)—— Attention Batch Normalization
  • 2023高教社杯数学建模C题思路代码 - 蔬菜类商品的自动定价与补货决策
  • 【C++漂流记】一文搞懂类与对象的封装
  • ctfshow 反序列化
  • 数据结构:线性表之-单向链表(无头)
  • 为IT服务台构建自定义Zia操作
  • 【C/C++】BMP格式32位转24位
  • 合宙Air724UG LuatOS-Air LVGL API控件-滑动条 (Slider)
  • SQLAlchemy 封装的工具类,数据库pgsql(数据库连接池)
  • 【Git】Git 基础
  • 腾讯云AI绘画:探究AI创意与技术的新边界
  • 离线数仓同步数据1
  • c语言开篇---跟着视频学C语言
  • 本地yum源-如学
  • 【实训】“宅急送”订餐管理系统(程序设计综合能力实训)
  • openeuler上安装polarismesh集群