You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java Stream遍历嵌套集合元素生成对应数组

实现方案

完全可以通过Stream实现需求,不需要手动写嵌套遍历逻辑,核心使用Stream的flatMap操作展开嵌套集合即可,代码简洁易读:

Operation[] allOperations = user.getUserTypes()
        .stream()
        // 提取每个用户角色对应的操作集合
        .map(UserType::getOperations)
        // 将多个Set<Operation>摊平为单个Operation元素的流
        .flatMap(Set::stream)
        // 转换为Operation数组
        .toArray(Operation[]::new);

可选优化(去重)

如果不同角色可能包含重复的Operation,需要去重的话,只需要在流中添加distinct()操作即可:

Operation[] distinctOperations = user.getUserTypes()
        .stream()
        .map(UserType::getOperations)
        .flatMap(Set::stream)
        // 去重,依赖Operation类的equals、hashCode实现
        .distinct()
        .toArray(Operation[]::new);

注意事项

  • 你的类上已经添加了Lombok的@Data注解,会自动生成equals和hashCode方法,distinct()会按照业务属性自动去重,无需额外处理。
  • Stream实现的性能和手写嵌套循环基本一致,同时可读性和可维护性更好。

内容的提问来源于stack exchange,提问作者AndreaNobili

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 09:54:08