top of page
Search

Java 8 Consumer Functional Interface Examples

  • schick09
  • Jan 22, 2024
  • 1 min read

Updated: Apr 25, 2024

java.util.function.Consumer is a functional interface introduced with Java 8.  This interface has two operations - 'accept' & 'andThen'.  I know what you're thinking - "Functional interfaces only have one operation". And you are right (sort of). The 'andThen' method is a static/default method. The 'accept' is the functional interface method.


The 'accept' operation's intention is to accept one parameter and perform an operation on that parameter.  It returns no value.

 

The following is an example of the accept operation. In this example, we create a function called 'multiply' that accepts a List of type Integer and multiples each Integer in the list by 2:


    public static void consumerExample(){
        Consumer<List<Integer>> multiply = list ->
        {
            for (int i = 0; i < list.size(); i++)
                list.set(i, 2 * list.get(i));
        };
        multiply.accept(numbers);
        for (Integer number: numbers){
            System.out.println(number);
        }
    }


 

The 'andThen' operation allows you to string two consumer operations together, executing them one after the other.  Perform the first and then perform the second.

 

In this example of the 'andThen' operation, we call our old friend 'multiply' and after it completes we call another consumer operation to print all of the Integers in the list:


    public static void consumerAndThenExample(){
        Consumer<List<Integer>> multiply = list ->
        {
            for (int i = 0; i < list.size(); i++)
                list.set(i, 2 * list.get(i));
        };
        Consumer<List<Integer>> print = list ->
        {
            for (int i = 0; i < list.size(); i++)
                System.out.println(list.get(i));
        };
        multiply.andThen(print).accept(numbers);
    }





 
 
 

Comments


Dave Schick Consulting

©2023 by Dave Schick Consulting. Proudly created with Wix.com

bottom of page