一、前言
在前面一篇文章中以Demo的形式介紹了Stream的API使用,其中peek和map看起來很像,這裏再詳細介紹一下。
二、管道流
一個流式也就是一條管道,操作分爲三步
- 數據準備
- 一步和多步中間操作,所有的操作都是懶操作,不會對數據產生影響
- 終止操作,數據輸出
三、 peek、map區別
peek入參是Consumer,沒有返回值
*
* @param action a <a href="package-summary.html#NonInterference">
* non-interfering</a> action to perform on the elements as
* they are consumed from the stream
* @return the new stream
*/
Stream<T> peek(Consumer<? super T> action);
map入參是Function,是需要返回值的
*
* @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);
顯而易見,當我們只需要對元素內部處理,使用peek是比較合適的,如果我們需要返回一個自定義的Stream時候,需要使用map
一般peek在Debug場景使用比較方便
/**
* peek map
*/
@Test
public void peekAndMapTest() {
//只需要訪問獲取內部元素,打印
List<String> stringList1 = Lists.newArrayList("11", "22", "33");
stringList1.stream().peek(System.out::print).collect(Collectors.toList());
List<String> stringList2 = Lists.newArrayList("11", "22", "33");
//支持自定義返回值,將字符串轉換爲數字
List<Integer> mapResultList = stringList2.stream().map(s -> Integer.valueOf(s)).collect(Collectors.toList());
System.out.println(mapResultList);
//可以看到返回值還是List<String>
List<String> peekResultList = stringList2.stream().peek(s -> Integer.valueOf(s)).collect(Collectors.toList());
System.out.println(peekResultList);
}
四、 peek、foreach區別
peek不會中斷流,後面可以對流繼續操作,foreach會中斷流,只能進行遍歷