• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Consumer Function andThen method

 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Guys,

in the below program i understand that the processing starts from the right side
so in the first accept method 5 is printed and incremented to 6.
and the  andthen method is suppose to print 6. However the output that i get is 56.
Can someone please clarify.

Thanks in Advance!!
 
Marshal
Posts: 75653
354
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How did you get 56 rather than 55?
 
Saloon Keeper
Posts: 13864
313
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Processing never starts from the right side.

You have an object of type Consumer which you call andThen() on, which yields a new Consumer. That resulting consumer can succinctly be described as "print and then print". In other words, it prints what you give to it twice.

i++ returns 5, so passing it to your consumer that prints its argument twice will result in "55" being printed.

I don't know where you got "56". It's incorrect.
 
Campbell Ritchie
Marshal
Posts: 75653
354
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:. . . I don't know where you got "56". It's incorrect.

I thought as much; I even tried it on JShell after getting suspicious.

jshell> Consumer<Integer> consumer = System.out::print;
  ...> Integer i = 5;
  ...> consumer.andThen(consumer).accept(i++);
consumer ==> $Lambda$28/0x0000000800c09c10@9807454
i ==> 5
55
jshell> i
i ==> 6

 
No matter. Try again. Fail again. Fail better. This time, do it with this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic