In continuation of our discussion on functional interfaces, Java 8 has provided many single method interfaces. Based on the abstract method’s signature Java has given them different names such as Consumer, Supplier, Function, BiFuction, Predicate etc. In this blog, we are going to discuss on Java Consumer and Supplier Interfaces.

1. Consumer functional interface.

Consumer functional interface is an interface having only one abstract method that accepts a single parameter and returns nothing. Here is how the interface looks like.

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

Here is an example of how Consumer interface can be used.

Consumer<String> c = x -> System.out.println(x.toLowerCase());  
c.accept("TestinG"); //Prints testing

1.1 Consumer functional interface chaining

One value can be passed to multiple consumers one after one. Here is an example.

Consumer<String> c1 = (x) -> System.out.println(x.toUpperCase());
Consumer<String> c2 = (x) -> System.out.println(x.length);

c1.andThen(c2).accept("testing"); // prints "TESTING" and then "7"

1.2 Primitive consumer types

Here are some primitive supplier types.

3. Supplier functional interface.

Supplier functional interface is an interface having only one abstract method doesn’t take any parameter but returns one value. This interface is used mainly to generate indefinite values in Java and also can be used in place of the factory patterns.

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

  Here is an example of how Consumer interface can be used.

Supplier<Double> random = Math::random;
random.get(); //Prints a random number

3.1 Primitive supplier types

Here are some primitive supplier types.

4. Conclusion

In this blog, we discussed two common type of interface supplier and consumer. Both the function interface are very frequently used in Java 8 Streams API.  We visited a little on primitive types of these interfaces. This is it about Java Consumer and Supplier Interfaces.