原代码是这样的:
List<Menu> children = all.stream().filter(...).map( (m) -> { m.setChildList(getChildrens(m, all)); return m; } ).collect(Collectors.toList());
其中 stream 用的 map 映射,其实更建议把 map 修改为 peek。
你可能会有这些疑问:
- 为什么要把 map 换成 peek 呢?怎么改?
- map 和 peek 有什么区别?
- peek 和 foreach 有什么区别?
看到这,你是不是彻底懵了,没问题,本篇栈长就来强势分析下!
另外,这些问题是 Java 程序员面试过程中必问的,出场率贼高,Java 程序员必懂,这些题我也都整理到了Java面试库小程序中,欢迎前往小程序刷题。
peek
map 和 peek 都是 Stream 提供的流处理方法。
首先看 peek 的使用源码注释:
This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline:
翻译:
这个方法主要用于支持 debug 调试,当你想看处于某个特定点的流元素时