![](https://img-blog.csdnimg.cn/img_convert/8e24eb891dffa2541e0a2ec4f6883b94.png)
本文介绍java 8 Stream流的常用高频api,通过实战级别的案例进行演示。实现结合实际业务、开发需要来应用技术,不让技术讲解枯燥无味,带来技术落地成生产力的价值。
1. 思考,stream 的多个操作,相当于几个for循环,实际执行了几次循环?
List<String> collect = strings.stream()
// peek1
.peek(e -> out.println("Original Element: " + e))
// filter
.filter(e -> e.length() > 3)
// peek2
.peek(e -> out.println("Filtered value: " + e))
//map
.map(String::toUpperCase)
//peek3
.peek(e -> out.println("Mapped value: " + e))
// collect
.collect(Collectors.toList());
2. Lambda 的 peek 和 forEach 区别
peek 返回值是和之前流泛型相同的流, 多用于打印中间操作时元素数据
forEach 没有返回值, 无法继续使用点语法操作
/**
* @author zhangcq
* @version 1.0.0
* @title
* @date 2022/6/9 13:50
*/
public class PeekAndForEachExample {
public static void main(String[] args) {
PrintStream out = System.out;
final List<String> strings
= Arrays.asList("one", "two", "three", "four");
List<String> result = new ArrayList<>();
/**~~~~~~~重点看这里~~~~~~~~~~~~~~~~~~~~**/
for (String e : strings) {
// peek1
out.println("Original Element: " + e);
// filter
if (e.length() > 3) {
// peek2
out.println("Filtered value: " + e);
//map
e = e.toUpperCase();
//peek3
out.println("Mapped value: " + e);
// collect
result.add(e);
}
}
System.out.println("stream collect: " + result);
out.println("Final Results: " + strings);
out.println("~~~~~~~~~~~~~~~~~~~~~");
List<String> collect = strings.stream()
// peek1</