java peek pop,在Java中,为什么stream 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 genre = new ArrayList(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());

解决方案

Because peek() accepts a Consumer.

A Consumer is designed to accept argument but returns no result.

For example here :

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

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().

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

List genre = new ArrayList(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,peek,pop)