如何提取过滤后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
相关产品推荐
相关产品推荐

