• 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:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Consumer different way

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

My question is on the below code.

I have written 2 consumers c1 and c2. While c1 is valid, c2 is giving an error. Why? How can  I fix it?

 
Bartender
Posts: 370
44
Firefox Browser MySQL Database Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
From the Java 11 docs for Consumer

@FunctionalInterface
public interface Consumer<T>

Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.

This is a functional interface whose functional method is accept(Object).


Consumer accepts one argument, but if you write those empty parentheses mean no arguments. For example a Supplier, which takes no arguments and returns a value, would look like this: Edit: Thanks Campbell for pointing out that it should have been Supplier<String>
 
Jj Roberts
Bartender
Posts: 370
44
Firefox Browser MySQL Database Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Passing a method reference to System.out.println() isn't going to work. A method reference is just a compact way to write a lambda. String::toUpperCase is the same as (String s) -> s.toUpperCase(); in this case. Your code is not calling toUpperCase on anything.

In fact, this will just attempt to print the value of the method reference itself. Trying it gives me the following: It tells us that there is no println method which takes a functional interface as an argument.
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic