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

如何将Java 7中的循环代码转换为Java 8实现?

这题我太熟啦!Java 8引入的Stream API刚好能帮你把这段循环代码简化得更简洁优雅,完全实现原功能的同时可读性还更强。

先回顾下你的Java 7代码:

List<String> childrenNames = Lists.newArrayList(); 
for (TreeItem child : children) { 
    childrenNames.add(child.toString()); 
}

下面给你两种Java 8的实现方式:

最常用的简洁写法

import java.util.stream.Collectors;

List<String> childrenNames = children.stream()
                                    .map(TreeItem::toString)
                                    .collect(Collectors.toList());

若需明确返回ArrayList(和原代码完全匹配)

Collectors.toList()返回的是通用List实现(不一定是ArrayList),如果要和原代码一样生成ArrayList实例,可以用下面的写法:

import java.util.ArrayList;
import java.util.stream.Collectors;

List<String> childrenNames = children.stream()
                                    .map(TreeItem::toString)
                                    .collect(Collectors.toCollection(ArrayList::new));

简单解释下逻辑:

  • children.stream():把集合转换为Stream流,开启函数式操作的入口
  • map(TreeItem::toString):将每个TreeItem对象映射为它的toString()结果,这里用的是方法引用,和lambda表达式child -> child.toString()效果完全一样
  • collect(...):把处理后的流收集成List集合,完成最终的结果转换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:48:56