在Java中,为什么Stream Peek对我不起作用? [英] In java, why stream peek is not working for me?

查看:607
本文介绍了在Java中,为什么Stream Peek对我不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在流上具有窥视功能,这是接受消费者的中间功能.那么在我的情况下,为什么不将"r"替换为"x". peek应该理想地用于调试目的,但是我只是想知道为什么它在这里不起作用.

we have peek function on stream which is intermediate function which accepts consumer. Then in my case why doesn't it replace "r" with "x". peek should ideally used for debugging purpose but I was just wondering why didn't it worked here.

List<String> genre = new ArrayList<String>(Arrays.asList("rock", "pop", "jazz", "reggae")); 
System.out.println(genre.stream().peek(s-> s.replace("r","x")).peek(s->System.out.println(s)).filter(s -> s.indexOf("x") == 0).count()); 

推荐答案

因为peek()接受Consumer.
Consumer旨在接受参数,但不返回任何结果.

Because peek() accepts a Consumer.
A Consumer is designed to accept argument but returns no result.

例如此处:

genre.stream().peek(s-> s.replace("r","x"))

s.replace("r","x")确实已执行,但它不会更改流的内容.
只是方法范围的String实例,在调用peek()之后不在范围之内.

s.replace("r","x") is indeed performed but it doesn't change the content of the stream.
It is just a method-scoped String instance that is out of the scope after the invocation of peek().

要进行测试,请将peek()替换为map():

To make your test, replace peek() by map() :

List<String> genre = new ArrayList<String>(Arrays.asList("rock", "pop", "jazz", "reggae"));
System.out.println(genre.stream().map(s -> s.replace("r", "x"))
                                 .peek(s -> System.out.println(s))
                                 .filter(s -> s.indexOf("x") == 0).count());

这篇关于在Java中,为什么Stream Peek对我不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆