Search code examples
javalambdajava-8java-stream

In java, why stream peek is not working for me?


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

Solution

  • 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<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());