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

如何提取过滤后MongoDB嵌套集合中DeviceType的对应Id字段

提取Id字段的实现方法

你现在已经拿到了过滤后的DeviceType集合,只需要通过Stream的map方法做字段映射就能提取Id,有两种常用写法:

  • 如果你要保留已经写好的中间集合filteredStartWithDeviceType,直接在这个集合的基础上做映射提取即可:
List<String> resultIds = filteredStartWithDeviceType.stream()
        .map(DeviceType::getId)
        .collect(Collectors.toList());
  • 更推荐的写法是跳过中间集合的生成,把过滤和字段提取合并到同一个Stream链路里,减少不必要的内存开销,代码更简洁:
List<String> resultIds = deviceTypes.stream()
        .filter(dt -> dt.getTelemetries().stream()
                .anyMatch(t -> t.getName().startsWith("System"))
        )
        .map(DeviceType::getId)
        .collect(Collectors.toList());

补充说明:如果需要去重,就在map之后、collect之前加.distinct();如果需要返回Set、拼接字符串等其他结果格式,替换Collectors对应的收集策略就行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.17 16:16:01