眾所周知在Java中使用Stream能夠很好地幫我們流處理對象。而Stream中有一個peek方法,它與map最大的區別是它沒有返回值。
一開始我是簡單地把它當做一個void類型的處理方法去使用的,但是后來卻發現程序執行到此處時,不進peek方法,也就是說peek根本就沒有被執行。
后來翻看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.
大意是說,僅在對流內元素進行操作時,peek才會被調用,當不對元素做任何操作時,peek自然也不會被調用了 - -...
最后,用foreach改寫了那段代碼,問題解決。
PS:其實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查看Stream內進行處理的每個元素。
好嘛,我承認是我眼瞎了...
最近更新了idea的版本,發現idea居然都有貼心的提示了!