• 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Consumer Function andThen method

 
Ranch Hand
Posts: 39
  • 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: 74004
332
  • 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: 13256
292
  • 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: 74004
332
  • 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

reply
    Bookmark Topic Watch Topic
  • New Topic