Consumer Functional Interface Example

Java 8 added a new functional interface named “Consumer”. The purpose of this interface is to consume/process the information received, it doesn’t return anything.

I will be explaining using the below example. In the example I have list of employees whom I want to terminate. I will pass the list of employees to an implementation of Consumer interface. The implementation will process
(i.e., terminate employees).

Consumer Interface Implementation


package Function;

import java.util.function.Consumer;

public class TerminateEmployees implements Consumer {
    @Override
    public void accept(Employee employee) {
        employee.setTerminated(true);
    }
}

According to the above code the implementation implements only one method named accepts which takes employee as parameter and terminate them.

The accept method doesn’t return anything. It just process the information.

Main code


1  package Function;
2  
3  import java.util.ArrayList;
4  import java.util.List;
5  
6  public class ConsumerDemo {
7   public static void main(String[] args) {
8       List list = new ArrayList();
9       
10      for(int i = 0; i < 5; i++) {
11          Employee employee = new Employee();
12          employee.setName("name"+i);
13          list.add(employee);
14      }
15      
16      System.out.println("Before Terminating");
17      for(Employee employee : list) {
18          System.out.println(employee);
19      }
20      
21      System.out.println();
22      
23      TerminateEmployees terminateEmployees = new TerminateEmployees();
24      for(Employee employee : list) {
25          terminateEmployees.accept(employee);
26      }
27      
28      System.out.println("After Terminating");
29      for(Employee employee : list) {
30          System.out.println(employee);
31      }
32  }
33 }

According to the code from line 23 to 26, we create an instance of TerminateEmployees. Then pass each and every employee to the implementation to get terminated.

Output

Before Terminating
name0:false
name1:false
name2:false
name3:false
name4:false

After Terminating
name0:true
name1:true
name2:true
name3:true
name4:true

Leave a Reply