文章目录
- [1. 逗号分隔的字符串转 List](#1. 逗号分隔的字符串转 List)
-
- [(1)转 `List<String>`](#(1)转
List<String>
) - [(2)转 `List<Long>`](#(2)转
List<Long>
)
- [(1)转 `List<String>`](#(1)转
- [2. map 元素映射](#2. map 元素映射)
- [3. filter 元素过滤](#3. filter 元素过滤)
- [4. findFirst 查找首个元素](#4. findFirst 查找首个元素)
-
- [(1)查找 filter 过滤后的首个元素](#(1)查找 filter 过滤后的首个元素)
- [5. groupingBy 分组](#5. groupingBy 分组)
1. 逗号分隔的字符串转 List
(1)转 List<String>
java
String str = "1,2,3,4,5,6";
List<String> list = Arrays.stream(str.split(","))
.map(String::trim).collect(Collectors.toList());
(2)转 List<Long>
java
String str = "1,2,3,4,5,6";
List<Long> list = Arrays.stream(str.split(","))
.map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
2. map 元素映射
java
List<String> usernameList = records.stream()
.map(SysUser::getUsername())
.collect(Collectors.toList());
3. filter 元素过滤
java
List<SysUser> sysUserList = records.stream()
.filter(x -> StrUtil.equals(x.getUsername(), "taibai"))
.collect(Collectors.toList());
4. findFirst 查找首个元素
(1)查找 filter 过滤后的首个元素
java
SysUser sysUser = records.stream()
.filter(x -> StrUtil.equals(x.getUsername(), "taibai"))
.findFirst().orElse(null);
5. groupingBy 分组
(1)单个字段分组
java
Map<String, SysUser> countMap = records.stream()
.collect(Collectors.groupingBy(SysUser::getDeptId()));
(2)单个字段分组-统计数量
java
Map<String, Long> countMap = records.stream()
.collect(Collectors.groupingBy(SysUser::getDeptId(), Collectors.counting()));
(3)多字段分组
java
Map<String, SysUser> countMap = records.stream()
.collect(Collectors.groupingBy(x -> x.getDeptId() + "_" + x.getRoleId()));
(4)多字段分组-统计数量
java
Map<String, Long> countMap = records.stream()
.collect(Collectors.groupingBy(x -> x.getProductType() + "_" + x.getCountry(), Collectors.counting()));