Core Java

Java 8 Functional Interface – Consumer Example

Hello. In this tutorial, we will explain the Consumer functional interface in java 8.

1. Introduction

Before diving deep into the practice stuff let us understand the Consumer functional interface in java programming. The interface:

java 8 Consumer
  • Contains the abstract accept() method and default andThen() method which can be used as an assignment for a lambda expression or method reference
  • Accepts a single argument and does not return any value

Let us understand the Consumer interface definition derived from the official documentation –

@FunctionalInterface
public interface Consumer<T> {
 
    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
 
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

2. Practice

Let us dive into some practice stuff from here and I am assuming that you already have the Java 1.8 or greater installed in your local machine. I am using JetBrains IntelliJ IDEA as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Model class implementation

Create a java file in the com.assignment.util package and add the following content to it. The file is acting as the model entity for students.

Student.java

package com.assignment.com.assignment.util;

import java.util.ArrayList;
import java.util.List;

public class Student {
    private final int id;
    private final String name;

    private Student(final int id, final String name) {
        this.id = id;
        this.name = name;
    }

    public static List<Student> createStudents() {
        final List<Student> students = new ArrayList<>();
        students.add(new Student(101, "John"));
        students.add(new Student(102, "Jane"));
        students.add(new Student(103, "Adam"));

        return students;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + getId() +
                ", name='" + getName() + '\'' +
                '}';
    }
}

2.2 Consumer interface implementation

Create a java file in the com.assignment package and add the following content to it. The file will show the Consumer functional interface implementation.

Example1.java

package com.assignment;

// Consumer functional interface

import com.assignment.com.assignment.util.Student;

import java.util.List;
import java.util.function.Consumer;

public class Example1 {

    // accept() method example
    private static void acceptImplementation() {
        final Consumer<String> stringConsumer = System.out::println;
        stringConsumer.accept("JavaCodeGeeks");
    }

    // andThen() method example
    private static void andThenImplementation() {
        final Consumer<String> first = x -> System.out.println(x.toLowerCase());
        final Consumer<String> second = y -> System.out.println(y.toUpperCase());

        final Consumer<String> result = first.andThen(second);
        result.accept("WebCodeGeeks");
    }

    // forEach() method example
    private static void forEachImplementation() {
        final List<Student> students = Student.createStudents();

        final Consumer<Student> studentConsumer = student -> System.out.println(student.toString());
        students.forEach(studentConsumer);
    }

    public static void main(String[] args) {
        System.out.println("----- Implementing accept() method -----");
        acceptImplementation();

        System.out.println("\n----- Implementing andThen() method -----");
        andThenImplementation();

        System.out.println("\n----- Implementing forEach() method -----");
        forEachImplementation();
    }
}

Run the file and if everything goes well the following output will be logged in the IDE console.

Console output

----- Implementing accept() method -----
JavaCodeGeeks

----- Implementing andThen() method -----
webcodegeeks
WEBCODEGEEKS

----- Implementing forEach() method -----
Student{id=101, name='John'}
Student{id=102, name='Jane'}
Student{id=103, name='Adam'}

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we learned the Consumer functional interface implementation. You can download the source code from the Downloads section.

4. Download the Eclipse Project

This was a tutorial where we implemented the Consumer functional interface in java 8.

Download
You can download the full source code of this example here: Java8 functional interface – Consumer tutorial

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button