Site iconJava PDF Blog

Java 8 Consumer Supplier Explained in 5 minutes

At IDR Solutions we use Java 8 for the development of our products (a Java PDF Viewer and SDKPDF to HTML5 converter and a Java ImageIO replacement). In this article, I will be looking at the Consumer Supplier.

What are these?

These features are functional interfaces (an interface with only one abstract method) that belong 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 let’s have a look at 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();
}

Let’s again have a look at 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

If you found this article useful, you may also be interested in our other Java8 posts on Lambda Expression, Streams API, Default MethodsMethod References, Optional and Repeating Annotations.

We also now have a large collection of articles on what is new in other versions of Java, including Java9, and Java13.