Java之字符串分割转换List

Java之字符串分割转换List

字符串分割成数组然后转换成List有多种方式,以下是每种方式的示例,推荐Java8的新特性Stream。

使用Java8的新特性Stream API

java 复制代码
String str = "aaa,bbb,ccc";  
// 使用Arrays.stream()  
List<String> list1 = Stream.of(str.split(",")).collect(Collectors.toList());  

// 使用Pattern.compile()与splitAsStream()  
List<String> list2 = Pattern.compile(",").splitAsStream(str).collect(Collectors.toList());  	

Arrays.asList()方法

java 复制代码
String str = "aaa,bbb,ccc";  
List<String> list = Arrays.asList(str.split(","));

//注意:Arrays.asList()返回的List是固定大小的,不支持添加或删除元素。
//如果需要可变的List,可以将其转换为ArrayList。
List<String> mutableList = new ArrayList<>(Arrays.asList(str.split(",")));

Guava库

1,maven添加依赖

xml 复制代码
<!-- Maven依赖 -->  
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>33.3.1-jre</version>
</dependency>

2,java代码

java 复制代码
String str = "aaa,bbb,ccc";
Iterable<String> iterable = Splitter.on(',').trimResults().split(str);  
List<String> list = Lists.newArrayList(iterable);

Apache Commons Lang库

1,maven添加依赖

xml 复制代码
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.17.0</version>
</dependency>

2,java代码

java 复制代码
String str = "aaa,bbb,ccc";
String[] array = StringUtils.split(str, ',');  
List<String> list1 = Arrays.asList(array); // 固定大小的List  
// 或者  
List<String> list2 = new ArrayList<>(Arrays.asList(array)); //可变的List  
相关推荐
华仔啊2 小时前
挖到了 1 个 Java 小特性:var,用完就回不去了
java·后端
SimonKing2 小时前
SpringBoot整合秘笈:让Mybatis用上Calcite,实现统一SQL查询
java·后端·程序员
日月云棠18 小时前
各版本JDK对比:JDK 25 特性详解
java
用户83071968408219 小时前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
JavaGuide19 小时前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
IT探险家20 小时前
Java 基本数据类型:8 种原始类型 + 数组 + 6 个新手必踩的坑
java
花花无缺20 小时前
搞懂new 关键字(构造函数)和 .builder() 模式(建造者模式)创建对象
java
用户9083246027320 小时前
Spring Boot + MyBatis-Plus 多租户实战:从数据隔离到权限控制的完整方案
java·后端
桦说编程21 小时前
实战分析 ConcurrentHashMap.computeIfAbsent 的锁冲突问题
java·后端·性能优化
埃博拉酱1 天前
VS Code Remote SSH 连接 Windows 服务器卡在"下载 VS Code 服务器":prcdn DNS 解析失败的诊断与 BITS 断点续传
windows·ssh·visual studio code