TechnologyZer
technologyzer.com

Introduction to Consumer Functional Interface

accept(T t) is an abstruct method in Consumer functional interface. It takes input and return nothing.

It has only one default method called andThen(), which is used for chaining.

public class Applicant {
    private String name;
    private String email;

    Applicant(String name, String email){
        this.name = name;
        this.email = email;
    }
    public String getName() {
        return name;
    }
    public String getEmail() {
        return email;
    }

    public void processApplication(Consumer<Applicant> applicationProcessor) {
        applicationProcessor.accept(this);
    }
}

public class Main {
    public static void main(String[] args) {
        Applicant newApplicant = new Applicant("Alice", "alice@gmail.com");

        Consumer<Applicant> emailSender = (Applicant applicant) ->{
            System.out.println("Sending confirmation email to: " + applicant.getEmail());
            System.out.println("Email send successfully");
        };

        Consumer<Applicant> databaseUpdater = (Applicant applicant) ->{
            System.out.println("Updating database with applicant information: ");
            System.out.println("Name: " + applicant.getName());
            System.out.println("Email: "+ applicant.getEmail());
            System.out.println("Database updated successfully..!");
        };

        newApplicant.processApplication(emailSender);
        newApplicant.processApplication(databaseUpdater);

        // instead of above two line, we can use andThen() default method of Consumer Interface.
        newApplicant.processApplication(emailSender.andThen(databaseUpdater));
    }
}

Leave a Comment