Search code examples
javafunctional-programmingfunctional-interface

Failing to see the point of the Functional interfaces 'Consumer' and 'Supplier'


I realize the uses of Predicate and Function, used for passing in a loosely-coupled conditional and function to a method respectively.

Predicates are frequently used for filtering java streams, e.g.

list.stream().filter(aPredicate).collect();

and Function:

list.stream().forEach(aFunction);

I don't see a similar use case for 'Consumer' and 'Supplier'. A simple example here has this code:

Consumer consumer = ConsumerTest::printNames;

consumer.accept("Jeremy");
consumer.accept("Paul");
consumer.accept("Richard");

where printNames is a simple method:

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

I don't see why I wouldn't just do:

Consumer consumer = ConsumerTest::printNames;

printNames("Jeremy");
printNames("Paul");
printNames("Richard");

Looks like unnecessary added code to me, perhaps that example does not show its power.


Solution

  • Your example of list.stream().forEach(aFunction); is actually wrong, forEach takes a Consumer<? super T> and not a Function<T,R>

    The point of these functional interfaces is all about the shape of the functions, in other words the inputs & outputs of these interfaces.

    To use the interfaces you provided:

    Predicate<T> input: value of type T, output: boolean, used by filter a lot.

    Function<T,R> input: value of type T, output: value of type R. Kinda like a transformation, used by map a lot.

    Consumer<T> input: value of type T, output: void/nothing. Used by forEach a lot, in situations where you just want to print something out, or persist the value to a database/file where you don't really care about the return value.

    Supplier<T> input: nothing, output: value of type T. This is probably the least common because people often start with a Collection when they use lambda. But Supplier is useful when you want to generate your own stream, for example, if you want to generate an infinite stream of prime numbers, there will be no way to do that by starting with a List.