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

如何将Java集合遍历代码改写为单行Stream流实现

改写后的一行Stream实现代码

// Java 16+ 版本
return ImmutableList.of(houseConstructor.newInstance(5, Houses.all().entrySet().stream().map(entry -> new Key<>(entry.getKey(), HousesTypes.getFor(entry.getValue()))).toList()));

如果是Java 8~15环境,替换toList()为collect(Collectors.toList())即可,需要提前导入java.util.stream.Collectors:

// Java 8~15 兼容版本
return ImmutableList.of(houseConstructor.newInstance(5, Houses.all().entrySet().stream().map(entry -> new Key<>(entry.getKey(), HousesTypes.getFor(entry.getValue()))).collect(Collectors.toList())));

逻辑说明

和原有代码完全等效:直接遍历Houses.all()的键值对集合,通过Stream的map操作将每一个Entry实例转换为对应的Key对象,收集为List后直接传入houseConstructor.newInstance方法,最后包裹为ImmutableList返回。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:09:03