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