「 Java 8 新特性 」Stream 中的 map、peek、foreach 方法的区别
创始人
2024-05-31 04:16:06
0

「 Java 8 新特性 」Stream 中的 map、peek、foreach 方法的区别

文章参考:

面试官问:Stream 中的 map、peek、foreach 方法的区别?傻傻分不清楚。。

stream中的map,peek,foreach的区别

一、概述

在学习java 8的stream api时,我们会遇到map,peek以及foreach这三种不同的处理方法,到底它们之间有些什么样的区别呢?本篇文章讲为你揭晓。

Map

/*** Returns a stream consisting of the results of applying the given* function to the elements of this stream.** 

This is an intermediate* operation.** @param The element type of the new stream* @param mapper a non-interfering,* stateless* function to apply to each element* @return the new stream*/ Stream map(Function mapper);

总结一下,就是应用一个函数型的接口,返回一个新流,是一个中间操作。

peek


/*** Returns a stream consisting of the elements of this stream, additionally* performing the provided action on each element as elements are consumed* from the resulting stream.** 

This is an intermediate* operation.**

For parallel stream pipelines, the action may be called at* whatever time and in whatever thread the element is made available by the* upstream operation. If the action modifies shared state,* it is responsible for providing the required synchronization.** @apiNote This method exists mainly to support debugging, where you want* to see the elements as they flow past a certain point in a pipeline:*

{@code*     Stream.of("one", "two", "three", "four")*         .filter(e -> e.length() > 3)*         .peek(e -> System.out.println("Filtered value: " + e))*         .map(String::toUpperCase)*         .peek(e -> System.out.println("Mapped value: " + e))*         .collect(Collectors.toList());* }
** @param action a * non-interfering action to perform on the elements as* they are consumed from the stream* @return the new stream*/Stream peek(Consumer action);

总结一下:接收一个消费型(Consumer)的接口,是一个中间操作,主要是用于debug的,可以进行二次的流处理

ForEach

/*** Performs an action for each element of this stream.** 

This is a terminal* operation.**

The behavior of this operation is explicitly nondeterministic.* For parallel stream pipelines, this operation does not* guarantee to respect the encounter order of the stream, as doing so* would sacrifice the benefit of parallelism. For any given element, the* action may be performed at whatever time and in whatever thread the* library chooses. If the action accesses shared state, it is* responsible for providing the required synchronization.** @param action a * non-interfering action to perform on the elements*/void forEach(Consumer action);

总结一下,接收一个消费型的接口,然后无返回值,是一个终止操作,注意线程安全问题及集合遍历的顺序问题。


二、示例

我们先创建一个集合用于测试

private List languageList = new ArrayList() {{add("java");add("python");add("c++");add("php");add("go");
}};

peek 方法中的函数式接口参数不能有返回值:

image-20230308082134379

意味着它不能像 map 一样处理流中的元素然后形成新流:

img

peek 不能修改流中的元素,只能对元素进行打印输出或者其他外部处理操作。

但流元素如果是引用类型,peek 却可以达到 map 的效果:

private List userList = new ArrayList() {{add(new User("张三"));add(new User("李四"));add(new User("王五"));add(new User("赵六"));
}};@Test
public void peekTest3() {userList.stream().peek(user -> user.setName("peek: " + user.getName())).forEach(System.out::println);
}

输出结果:

SteamPeekTest.User(name=peek: 张三)
SteamPeekTest.User(name=peek: 李四)
SteamPeekTest.User(name=peek: 王五)
SteamPeekTest.User(name=peek: 赵六)

虽然不能有返回值形成新的流,但却可以修改引用类型字段的值。

这也是建议的为什么要把 map 换成 peek 了,因为是引用类型,使用 peek 就没必要 set 之后还要进行 return 了。

List children = all.stream().filter(...).map((m) -> {m.setChildList(getChildrens(m, all));return m;}
).collect(Collectors.toList());

修改为:

List children = all.stream().filter(...).peek(m -> m.setChildList(getChildrens(m, all))
).collect(Collectors.toList());

是不是优雅多了?

peek 和 foreach 有什么区别?

Foreach 和 peek 一样也是接收 Consumer 参数,不同是 foreach 没有返回参数,意味着 foreach 会中断流操作,只能用来遍历,不能再进行后续的流处理。


三、小结

根据文中的示例,大家应该都搞清楚了 map、peek、foreach 的区别和用法了,现在再来总结下吧!

  • map:用于对流中的每个元素进行映射处理,然后再形成新的流;
  • peek:用于 debug 调试流中间结果,不能形成新的流,但能修改引用类型字段的值;
  • foreach:用于遍历,会中断流操作;

所以说,大家都搞清楚了吧?还有谁用错,把这篇文章发给他吧,让大家少走弯路,少写垃圾代码,共同进步。

相关内容

热门资讯

前端-session、jwt 目录:   (1)session (2&#x...
linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
前缀和与对数器与二分法 1. 前缀和 假设有一个数组,我们想大量频繁的去访问L到R这个区间的和,...
nodejs:本地安装nvm实... 一、背景-使用不同版本node的原因 vue3+ts、nuxt3版本,node...
JAVA集合知识整理 Java集合知识整理 HashMap相关 HashMap的底层数据结构:jdk1.8之...
无刷直流电机介绍及单片机控制实... 无刷直流电机介绍及单片机控制实例前言基本概念优势与劣势使用寿命基本结构使用单片机控制实例电子调速器&...
fwdiary(2) dp2 1.传纸条  AcWing 275. 传纸条 - AcWing 走两条路,走一条最大的...
常用的DOS命令 常用的DOS命令 DOS(Disk Operating System,磁...
<C++> 类和对象(下) 1.const成员函数将const修饰的“成员函数”称之为const成员函数,cons...