SoFunction
Updated on 2025-03-08

Detailed explanation of the usage example of the Consumer of Java 8 Functional Interface

Java 8 Functional Interface Consumer

Consumer<T>It is a predefined functional interface in Java 8, which is used to accept an input parameter.TAnd perform some operations but no return value.

Consumer<T>An abstract method is defined in the interfacevoid accept(T t), this method accepts a parametert, indicates the operation to be performed. You can useaccept()Methods to define specific operation logic.

Using the Consumer<T> interface

Sample code

import ;
import ;
import ;
public class ConsumerExample {
    public static void main(String[] args) {
        // Define a list of strings        List&lt;String&gt; fruits = ("Apple", "Orange", "Banana", "Mango");
        // Use the Consumer interface to implement the operation of traversing and outputting each fruit        Consumer&lt;String&gt; printFruit = fruit -&gt; (fruit);
        (printFruit);
        // Can be simplified to the following form        (::println);
    }
}

Print result:

Apple
Orange
Banana
Mango

In the example above, we first create a list of string fruits, and then create aConsumer<String>Object printFruit, implemented through lambda expressionaccept()The specific operation of the method is to print the name of each fruit.

useforEach()Combination of methodsConsumerInterface, which can simplify traversing the list and perform specified operations.

forEach() method source code

default void forEach(Consumer<? super T> action) {
        (action);
        for (T t : this) {
            (t);
        }
    }

existforEachIn the implementation of the method, first check the incomingactionWhether it is null, and if it is null, a NullPointerException will be thrown. It then uses an enhanced for loop to traverse this (i.e. the current Iterable object) to execute on each element(t),intis the current element.

The above is a detailed explanation of the usage example of the Java 8 functional interface Consumer. For more information about Java 8 functional interface Consumer, please pay attention to my other related articles!