【Java】讲讲StreamAPI

 

预设场景:

从Mybatis调用Mapper得到的用户集合

1
List<UserDTO> userList = new ArrayList<>();

 

常用的几种API用法示例:

Map方法,转换为某一个字段的集合:

1
2
3
4
List<Integer> userIdList = userList.stream()
                /* map 转换成某个类型来处理,比如这个场景是为了快速提取用户id */
                .map(UserDTO::getId)
                .collect(Collectors.toList());

 

Distinct方法,对基本类型支持去重处理:

1
2
3
4
List<Integer> distinctUserIds = userIdList.stream()
        /* distinct 可对元素进行去重,推荐类型是基础包装类和String两种 */
        .distinct()
        .collect(Collectors.toList());

 

FlatMap方法,支持更深维度的处理:

1
2
3
4
5
6
7
List<String> fun1 = Arrays.asList("one", "two", "three");
List<String> fun2 = Arrays.asList("four", "five", "six");
List<List<String>> nestedList = Arrays.asList(fun1, fun2);
nestedList.stream()
        /* flatMap 可以支持更深维度的集合转换,stream合并处理 */
        .flatMap(x -> x.stream()).map(x->x.toUpperCase())
        .forEach(System.out::println);

 

Filter方法,根据条件对集合进行过滤处理

检查名称是否包含张字的用户

1
2
3
4
5
List<UserDTO> matchUsers = userList.stream()
        /* filter 用于检索匹配条件方法的元素 */
        .filter(user -> user.getUserName().contains("张"))
        /* 存在多个情况可以使用 toList 收集匹配的元素 */
        .collect(Collectors.toList());

  

FindFirst和FindAny方法,筛选为单个

1
2
3
4
5
UserDTO userDTO = matchUsers.stream()
        .filter(user -> "1001".equals(user.getId().toString()))
        /* 或者使用 findFirst && findAny 提取唯一一个元素  */
        .findFirst()
        .get();

  

AnyMatch与AllMatch 对集合进行匹配判断:

1
2
3
boolean anyMatch = userList.stream()
        /* anyMatch 检查任意元素是否符合匹配方法,反之 allMatch 要求所有元素符合 */
        .anyMatch(user -> 3001 > user.getId());

  

GroupBy 等同SQL的GroupBy,但是只能是单个字段的

1
2
3
Map<String, List<UserDTO>> userGroupMap = userList.stream()
        /* groupingBy 指定以什么值作为分组的条件,这里以用户的组名称进行分组 */
        .collect(Collectors.groupingBy(UserDTO::getGroupName));

  

PartitionBy 则根据你的自定义的方法具体分组,但是只有true和false两种:

1
2
3
4
final Integer superPermit = 1001;
Map<Boolean, List<UserDTO>> permitPartMap = userList.stream()
        /* partitioningBy 使用条件进行分区处理,场景:检查是不是超级权限的用户, 分区为 超级权限用户(true)和非超级权限用户(false) */
        .collect(Collectors.partitioningBy(user -> user.getRoleIds().contains(superPermit)));

 

Skip与Limit 对集合支持翻页操作:

1
2
3
4
/* 用于集合的翻页操作, 等同SQL的LIMIT 10, 20 */
List<UserDTO> collect = userList.stream()
        .skip(10).limit(20)
        .collect(Collectors.toList());

  

Reduce 对集合进行聚合操作:

1
2
3
4
/* reduce用于聚合处理,例如合计这个用户集合的现金 */
BigDecimal userCashAmount = userList.stream()
        .map(UserDTO::getAmount)
        .reduce(new BigDecimal(0), BigDecimal::add);

  

 

  

 

posted @   emdzz  阅读(19)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示