对 Stream 中 Map 与 ForEach 做个简单说明
經(jīng)常會(huì)有童鞋把 Map 和 Foreach 用錯(cuò),可能會(huì)出現(xiàn)如下用法:
List<Student> studentChangeList = studentList.stream().forEach(student -> student.setAge(99));有些編譯器會(huì)直接報(bào)錯(cuò),比如 IDEA。因?yàn)?ForEach 是沒(méi)有返回值的,ForEach 處理過(guò)的 Stream 是無(wú)法再賦值給 studentChangeList 。
但是現(xiàn)在就是需要對(duì)集合進(jìn)行處理,并獲取處理過(guò)的集合數(shù)據(jù),這時(shí)候可以這樣做
studentList.stream().forEach(student -> student.setAge(99));studentList 中的數(shù)據(jù)就是已經(jīng)處理過(guò)的數(shù)據(jù)。
下面就 Map 和 ForEach 做一些簡(jiǎn)單的說(shuō)明,大體上就能對(duì)這兩個(gè)方法有所理解
一、 結(jié)論
Map:返回的是一個(gè)新流,可以對(duì)這個(gè)流進(jìn)一步操作
ForEach:返回void,即無(wú)返回值
二、源碼
1. Map 源碼說(shuō)明
/*** Returns a stream consisting of the results of applying the given* function to the elements of this stream.** <p>This is an <a href="package-summary.html#StreamOps">intermediate* operation</a>.** @param <R> The element type of the new stream* @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,* <a href="package-summary.html#Statelessness">stateless</a>* function to apply to each element* @return the new stream*/<R> Stream<R> map(Function<? super T, ? extends R> mapper);2. ForEach 源碼說(shuō)明
/*** Performs an action for each element of this stream.** <p>This is a <a href="package-summary.html#StreamOps">terminal* operation</a>.** <p>The behavior of this operation is explicitly nondeterministic.* For parallel stream pipelines, this operation does <em>not</em>* 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 <a href="package-summary.html#NonInterference">* non-interfering</a> action to perform on the elements*/void forEach(Consumer<? super T> action);三、應(yīng)用
1.Map 是1對(duì)1的映射
示例:
將兩位同學(xué)的年齡都加上100
運(yùn)行結(jié)果:
117 1182.ForEach 是對(duì) Stream 中每一個(gè)元素進(jìn)行處理。
雖然 ForEach 處理 Stream 中元素的時(shí)候沒(méi)有返回值,但是 ForEach 對(duì) Stream 中元素已經(jīng)產(chǎn)生影響,即 ForEach 對(duì) Stream 中元素的操作已經(jīng)被保存下來(lái)。
示例:
將兩位同學(xué)的年齡改為99,名字改為英俊
運(yùn)行結(jié)果:
Student(studentId=1, studentName=英俊, age=99) Student(studentId=2, studentName=英俊, age=99)總結(jié)
以上是生活随笔為你收集整理的对 Stream 中 Map 与 ForEach 做个简单说明的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 阿里云自营建站买一年送一年
- 下一篇: 手持终端机USB无法同步连接是什么意思?