Java: Consumer interface in a stream doesn't work as expected [duplicate]












3
















This question already has an answer here:




  • Java 8 Streams peek api

    4 answers



  • How to use Streams api peek() function and make it work?

    2 answers




I've got 2 statements, I expected that they should "print" same result:



Arrays.stream("abc".split("")).forEach(System.out::println);//first
Arrays.stream("abc".split("")).peek(new Consumer<String>() {//second
@Override
public void accept(String s) {
System.out.println(s);//breakpoint
}
});


In fact, the first statement will print



a
b
c


Ok, but the second statement prints nothing. I tried to set a breakpoint in the line of "//breakpoint" inside IntelliJ, but it wasn't hit.



So how should I change the second statement to use "peek" as it create a new stream while processing every element using "Consumer"?



Thanks a lot.










share|improve this question















marked as duplicate by Sotirios Delimanolis java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 24 '18 at 18:10


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • 1





    Peek is an intermediate operation.

    – ema
    Nov 24 '18 at 7:12
















3
















This question already has an answer here:




  • Java 8 Streams peek api

    4 answers



  • How to use Streams api peek() function and make it work?

    2 answers




I've got 2 statements, I expected that they should "print" same result:



Arrays.stream("abc".split("")).forEach(System.out::println);//first
Arrays.stream("abc".split("")).peek(new Consumer<String>() {//second
@Override
public void accept(String s) {
System.out.println(s);//breakpoint
}
});


In fact, the first statement will print



a
b
c


Ok, but the second statement prints nothing. I tried to set a breakpoint in the line of "//breakpoint" inside IntelliJ, but it wasn't hit.



So how should I change the second statement to use "peek" as it create a new stream while processing every element using "Consumer"?



Thanks a lot.










share|improve this question















marked as duplicate by Sotirios Delimanolis java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 24 '18 at 18:10


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • 1





    Peek is an intermediate operation.

    – ema
    Nov 24 '18 at 7:12














3












3








3


1







This question already has an answer here:




  • Java 8 Streams peek api

    4 answers



  • How to use Streams api peek() function and make it work?

    2 answers




I've got 2 statements, I expected that they should "print" same result:



Arrays.stream("abc".split("")).forEach(System.out::println);//first
Arrays.stream("abc".split("")).peek(new Consumer<String>() {//second
@Override
public void accept(String s) {
System.out.println(s);//breakpoint
}
});


In fact, the first statement will print



a
b
c


Ok, but the second statement prints nothing. I tried to set a breakpoint in the line of "//breakpoint" inside IntelliJ, but it wasn't hit.



So how should I change the second statement to use "peek" as it create a new stream while processing every element using "Consumer"?



Thanks a lot.










share|improve this question

















This question already has an answer here:




  • Java 8 Streams peek api

    4 answers



  • How to use Streams api peek() function and make it work?

    2 answers




I've got 2 statements, I expected that they should "print" same result:



Arrays.stream("abc".split("")).forEach(System.out::println);//first
Arrays.stream("abc".split("")).peek(new Consumer<String>() {//second
@Override
public void accept(String s) {
System.out.println(s);//breakpoint
}
});


In fact, the first statement will print



a
b
c


Ok, but the second statement prints nothing. I tried to set a breakpoint in the line of "//breakpoint" inside IntelliJ, but it wasn't hit.



So how should I change the second statement to use "peek" as it create a new stream while processing every element using "Consumer"?



Thanks a lot.





This question already has an answer here:




  • Java 8 Streams peek api

    4 answers



  • How to use Streams api peek() function and make it work?

    2 answers








java java-8 java-stream consumer peek






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 7:41









Nicholas K

7,32661435




7,32661435










asked Nov 24 '18 at 7:02









TroskyvsTroskyvs

2,39221232




2,39221232




marked as duplicate by Sotirios Delimanolis java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 24 '18 at 18:10


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by Sotirios Delimanolis java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 24 '18 at 18:10


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.










  • 1





    Peek is an intermediate operation.

    – ema
    Nov 24 '18 at 7:12














  • 1





    Peek is an intermediate operation.

    – ema
    Nov 24 '18 at 7:12








1




1





Peek is an intermediate operation.

– ema
Nov 24 '18 at 7:12





Peek is an intermediate operation.

– ema
Nov 24 '18 at 7:12












4 Answers
4






active

oldest

votes


















3














Stream.peek, as stated in the javadocs of the API as well, is meant mainly for debugging purposes and performing any update operations on the stream during the peek operation is not recommended.



For example, you can verify the intermediate stream state with the following code and what it eventually results in:



Arrays.stream("acb".split(""))
.peek(System.out::println) // print a c b
.sorted()
.forEach(System.out::println); // print a b c


In general, this operation is an intermediate operation wouldn't be executed unless and terminal operation is performed on the stream as mentioned in the Stream operations and pipelines section of the docs and that is exactly the reason why your first statement will print.



Note: Though as suggested in a few other answers, the action within peek
is not invoked in the cases when its able to optimize the result for some short-circuiting operations like findFirst etc.




In cases where the stream implementation is able to optimize away the
production of some or all the elements (such as with short-circuiting
operations like findFirst, or in the example described in count()),
the action will not be invoked for those elements.







share|improve this answer


























  • Suggested Read: Answer: In Java streams is peek really only for debugging?

    – nullpointer
    Nov 24 '18 at 7:49



















3














peek() is not terminal operation, you need to add any terminal operation to make peek work, e.g.



Arrays.stream("abc".split("")).peek(new Consumer<String>() { //second
@Override
public void accept(String s) {
System.out.println(s);//breakpoint
}
}).count();





share|improve this answer





















  • 2





    not a good idea to perform short-circuiting operations like count with peek, as when the operation is optimized the action would not be invoked.

    – nullpointer
    Nov 24 '18 at 7:27



















1














The peek() is not a terminal operation, it produces an intermediate stream. Your stream would be executed only when it finds a terminal operation.



For eg: if you add the count() terminal operation to your second stream, you will get the expected output.



Note - You got an output for the first stream because forEach() is a terminal operation.






share|improve this answer































    1














    Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy. So, Steam will start executing the operation pipeline once it gets any terminal operation. In your first case forEach is the terminal operation, so the stream executed. But in the second ca,se the last operation in the pipeline is peek() which is not a terminal operation.






    share|improve this answer






























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      Stream.peek, as stated in the javadocs of the API as well, is meant mainly for debugging purposes and performing any update operations on the stream during the peek operation is not recommended.



      For example, you can verify the intermediate stream state with the following code and what it eventually results in:



      Arrays.stream("acb".split(""))
      .peek(System.out::println) // print a c b
      .sorted()
      .forEach(System.out::println); // print a b c


      In general, this operation is an intermediate operation wouldn't be executed unless and terminal operation is performed on the stream as mentioned in the Stream operations and pipelines section of the docs and that is exactly the reason why your first statement will print.



      Note: Though as suggested in a few other answers, the action within peek
      is not invoked in the cases when its able to optimize the result for some short-circuiting operations like findFirst etc.




      In cases where the stream implementation is able to optimize away the
      production of some or all the elements (such as with short-circuiting
      operations like findFirst, or in the example described in count()),
      the action will not be invoked for those elements.







      share|improve this answer


























      • Suggested Read: Answer: In Java streams is peek really only for debugging?

        – nullpointer
        Nov 24 '18 at 7:49
















      3














      Stream.peek, as stated in the javadocs of the API as well, is meant mainly for debugging purposes and performing any update operations on the stream during the peek operation is not recommended.



      For example, you can verify the intermediate stream state with the following code and what it eventually results in:



      Arrays.stream("acb".split(""))
      .peek(System.out::println) // print a c b
      .sorted()
      .forEach(System.out::println); // print a b c


      In general, this operation is an intermediate operation wouldn't be executed unless and terminal operation is performed on the stream as mentioned in the Stream operations and pipelines section of the docs and that is exactly the reason why your first statement will print.



      Note: Though as suggested in a few other answers, the action within peek
      is not invoked in the cases when its able to optimize the result for some short-circuiting operations like findFirst etc.




      In cases where the stream implementation is able to optimize away the
      production of some or all the elements (such as with short-circuiting
      operations like findFirst, or in the example described in count()),
      the action will not be invoked for those elements.







      share|improve this answer


























      • Suggested Read: Answer: In Java streams is peek really only for debugging?

        – nullpointer
        Nov 24 '18 at 7:49














      3












      3








      3







      Stream.peek, as stated in the javadocs of the API as well, is meant mainly for debugging purposes and performing any update operations on the stream during the peek operation is not recommended.



      For example, you can verify the intermediate stream state with the following code and what it eventually results in:



      Arrays.stream("acb".split(""))
      .peek(System.out::println) // print a c b
      .sorted()
      .forEach(System.out::println); // print a b c


      In general, this operation is an intermediate operation wouldn't be executed unless and terminal operation is performed on the stream as mentioned in the Stream operations and pipelines section of the docs and that is exactly the reason why your first statement will print.



      Note: Though as suggested in a few other answers, the action within peek
      is not invoked in the cases when its able to optimize the result for some short-circuiting operations like findFirst etc.




      In cases where the stream implementation is able to optimize away the
      production of some or all the elements (such as with short-circuiting
      operations like findFirst, or in the example described in count()),
      the action will not be invoked for those elements.







      share|improve this answer















      Stream.peek, as stated in the javadocs of the API as well, is meant mainly for debugging purposes and performing any update operations on the stream during the peek operation is not recommended.



      For example, you can verify the intermediate stream state with the following code and what it eventually results in:



      Arrays.stream("acb".split(""))
      .peek(System.out::println) // print a c b
      .sorted()
      .forEach(System.out::println); // print a b c


      In general, this operation is an intermediate operation wouldn't be executed unless and terminal operation is performed on the stream as mentioned in the Stream operations and pipelines section of the docs and that is exactly the reason why your first statement will print.



      Note: Though as suggested in a few other answers, the action within peek
      is not invoked in the cases when its able to optimize the result for some short-circuiting operations like findFirst etc.




      In cases where the stream implementation is able to optimize away the
      production of some or all the elements (such as with short-circuiting
      operations like findFirst, or in the example described in count()),
      the action will not be invoked for those elements.








      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 24 '18 at 7:34

























      answered Nov 24 '18 at 7:22









      nullpointernullpointer

      43k10101198




      43k10101198













      • Suggested Read: Answer: In Java streams is peek really only for debugging?

        – nullpointer
        Nov 24 '18 at 7:49



















      • Suggested Read: Answer: In Java streams is peek really only for debugging?

        – nullpointer
        Nov 24 '18 at 7:49

















      Suggested Read: Answer: In Java streams is peek really only for debugging?

      – nullpointer
      Nov 24 '18 at 7:49





      Suggested Read: Answer: In Java streams is peek really only for debugging?

      – nullpointer
      Nov 24 '18 at 7:49













      3














      peek() is not terminal operation, you need to add any terminal operation to make peek work, e.g.



      Arrays.stream("abc".split("")).peek(new Consumer<String>() { //second
      @Override
      public void accept(String s) {
      System.out.println(s);//breakpoint
      }
      }).count();





      share|improve this answer





















      • 2





        not a good idea to perform short-circuiting operations like count with peek, as when the operation is optimized the action would not be invoked.

        – nullpointer
        Nov 24 '18 at 7:27
















      3














      peek() is not terminal operation, you need to add any terminal operation to make peek work, e.g.



      Arrays.stream("abc".split("")).peek(new Consumer<String>() { //second
      @Override
      public void accept(String s) {
      System.out.println(s);//breakpoint
      }
      }).count();





      share|improve this answer





















      • 2





        not a good idea to perform short-circuiting operations like count with peek, as when the operation is optimized the action would not be invoked.

        – nullpointer
        Nov 24 '18 at 7:27














      3












      3








      3







      peek() is not terminal operation, you need to add any terminal operation to make peek work, e.g.



      Arrays.stream("abc".split("")).peek(new Consumer<String>() { //second
      @Override
      public void accept(String s) {
      System.out.println(s);//breakpoint
      }
      }).count();





      share|improve this answer















      peek() is not terminal operation, you need to add any terminal operation to make peek work, e.g.



      Arrays.stream("abc".split("")).peek(new Consumer<String>() { //second
      @Override
      public void accept(String s) {
      System.out.println(s);//breakpoint
      }
      }).count();






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Dec 27 '18 at 3:54









      nullpointer

      43k10101198




      43k10101198










      answered Nov 24 '18 at 7:07









      Evgeniy DorofeevEvgeniy Dorofeev

      106k23143223




      106k23143223








      • 2





        not a good idea to perform short-circuiting operations like count with peek, as when the operation is optimized the action would not be invoked.

        – nullpointer
        Nov 24 '18 at 7:27














      • 2





        not a good idea to perform short-circuiting operations like count with peek, as when the operation is optimized the action would not be invoked.

        – nullpointer
        Nov 24 '18 at 7:27








      2




      2





      not a good idea to perform short-circuiting operations like count with peek, as when the operation is optimized the action would not be invoked.

      – nullpointer
      Nov 24 '18 at 7:27





      not a good idea to perform short-circuiting operations like count with peek, as when the operation is optimized the action would not be invoked.

      – nullpointer
      Nov 24 '18 at 7:27











      1














      The peek() is not a terminal operation, it produces an intermediate stream. Your stream would be executed only when it finds a terminal operation.



      For eg: if you add the count() terminal operation to your second stream, you will get the expected output.



      Note - You got an output for the first stream because forEach() is a terminal operation.






      share|improve this answer




























        1














        The peek() is not a terminal operation, it produces an intermediate stream. Your stream would be executed only when it finds a terminal operation.



        For eg: if you add the count() terminal operation to your second stream, you will get the expected output.



        Note - You got an output for the first stream because forEach() is a terminal operation.






        share|improve this answer


























          1












          1








          1







          The peek() is not a terminal operation, it produces an intermediate stream. Your stream would be executed only when it finds a terminal operation.



          For eg: if you add the count() terminal operation to your second stream, you will get the expected output.



          Note - You got an output for the first stream because forEach() is a terminal operation.






          share|improve this answer













          The peek() is not a terminal operation, it produces an intermediate stream. Your stream would be executed only when it finds a terminal operation.



          For eg: if you add the count() terminal operation to your second stream, you will get the expected output.



          Note - You got an output for the first stream because forEach() is a terminal operation.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 24 '18 at 7:06









          Nicholas KNicholas K

          7,32661435




          7,32661435























              1














              Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy. So, Steam will start executing the operation pipeline once it gets any terminal operation. In your first case forEach is the terminal operation, so the stream executed. But in the second ca,se the last operation in the pipeline is peek() which is not a terminal operation.






              share|improve this answer




























                1














                Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy. So, Steam will start executing the operation pipeline once it gets any terminal operation. In your first case forEach is the terminal operation, so the stream executed. But in the second ca,se the last operation in the pipeline is peek() which is not a terminal operation.






                share|improve this answer


























                  1












                  1








                  1







                  Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy. So, Steam will start executing the operation pipeline once it gets any terminal operation. In your first case forEach is the terminal operation, so the stream executed. But in the second ca,se the last operation in the pipeline is peek() which is not a terminal operation.






                  share|improve this answer













                  Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy. So, Steam will start executing the operation pipeline once it gets any terminal operation. In your first case forEach is the terminal operation, so the stream executed. But in the second ca,se the last operation in the pipeline is peek() which is not a terminal operation.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 24 '18 at 7:15









                  Amit BeraAmit Bera

                  3,6951628




                  3,6951628















                      Popular posts from this blog

                      Create new schema in PostgreSQL using DBeaver

                      Deepest pit of an array with Javascript: test on Codility

                      Fotorealismo