Java 8 Consumer Supplier Explained in 5 minutes

In my previous Java 8 series articles, we discussed Lambda Expression, Streams API, Default Methods and Method References. and Repeating Annotations. This time we will be looking at Consumer Supplier.

What are these?

These features are functional interfaces (an interface with only one abstract method) which belongs to the java.util.function package.

The consumer accepts a single argument by calling its accept (args) method and does not return any value making it a void method.

@FunctionalInterface
public interface Consumer {
  void accept(T t);
}

Now Lets have a look of a simple code example where the Consumer interface is being used.

import java.util.function.Consumer;
 
public class ConsumerTest {
 
 
 
    public static void main(String[] args) {
 
 
Consumer consumer = ConsumerTest::printNames;
 
 
consumer.accept("Jeremy");
consumer.accept("Paul");
consumer.accept("Richard");
 
    } 
 
    private static void printNames(String name) {
        System.out.println(name);
    }
}

Jeremy
Paul
Richard

The supplier does the opposite of the consumer, so it takes no arguments but it returns some value by calling its get() method.
Note: This may return different values when it is being called more than once.

@FunctionalInterface
public interface Supplier {
  T get();
}

Lets again have a look of a simple code example where the Supplier interface is being used.

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
 
public class SupplierTest {
 
 
 
    public static void main(String[] args) {
 
 
        List  names = new ArrayList(); 
        names.add( "David");
        names.add( "Sam");
   names.add( "Ben");
 
        names.stream().forEach((x) -> {
            printNames(() -> x);
        });
 
    }
 
      static void printNames(Supplier arg) {
System.out.println(arg.get());
    }
}

David
Sam
Ben

Hopefully you have found this quick guide useful.

We now have a series of articles on what is new in Java 9:

If you’re a first-time reader, or simply want to be notified when we post new articles and updates, you can keep up to date by social media (Twitter, Facebook and Google+) or the Blog RSS.

Related Posts:

The following two tabs change content below.

Ernest Duodu

Developer at IDRSolutions
Ernest is a developer at IDRSolutions. He focuses mainly on our JavaFX PDF Viewer implementation. He was a speaker at JavaOne 2014, where he did a joint session titled "Lessons learnt developing a NetBeans PDF viewer plugin in JavaFX". Aside programming, he also enjoys a wide variety of hobbies which includes sky-diving, photography, exercising and listening to music.
Ernest

About Ernest Duodu

Ernest is a developer at IDRSolutions. He focuses mainly on our JavaFX PDF Viewer implementation. He was a speaker at JavaOne 2014, where he did a joint session titled "Lessons learnt developing a NetBeans PDF viewer plugin in JavaFX". Aside programming, he also enjoys a wide variety of hobbies which includes sky-diving, photography, exercising and listening to music.

14 thoughts on “Java 8 Consumer Supplier Explained in 5 minutes

  1. Binh Thanh Nguyen

    Thanks, nice explanation

  2. M G

    I think you need to use


    Consumer consumer = ConsumerTest::printNames;

    in the Consumer example in order to have it compiling.

  3. Oleg

    The method printNames() should probably be called printName() since it prints only one name per call.

  4. Paul

    The greaterThan symbol used when declaring lambda for the forEach block is not displayed correctly (i.e. the characters for ampersand, g, t and semicolon are displayed).

    • Hi Paul,

      Thank you for pointing this out to us, I have adjusted the code and it should be working fine now.

  5. Raghava

    Consumer consumer = (x) -> printNames(x);

  6. Clark

    Eclipse: cannot compile
    @FunctionalInterface
    public interface Consumer {
    void accept(T t);
    }
    compiler error: T cannot be solved as a type

    Consumer consumer = ConsumerTest::printNames;
    compiler error:Multiple errors….

    • Raed

      Hello Clark i got the same with Eclipse

      • sridhar

        You need to type cast the consumer, to make it work .

        Consumer consumer = ConsumerTest::printNames;

  7. sridhar

    Consumer &gt String &lt consumer = ConsumerTest::printNames;

  8. Hi, replace this to make it works in the Consumer example:

    private static void printNames(Object name) {
    System.out.println(name);
    }

  9. SOURABH VERMA

    import java.util.function.Consumer;

    public class ConsumerExample {
    public static void main(String[] args) {
    Consumer consumer = (x) -> printNames(x);
    consumer.accept(“Jeremy”);
    consumer.accept(“Paul”);
    consumer.accept(“Richard”);
    }

    private static void printNames(Object name) {
    System.out.println(name);
    }
    }

  10. Jiri

    Thx for the example 🙂
    Consumer must be of type String, if method reference is used:
    Consumerconsumer = ConsumerTest::printNames;

  11. krishna

    How to make a consumer to save the input parameter to a database?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>