SoFunction
Updated on 2025-03-04

How to implement multiple parameters in Consumer and Supply in Java?

The Java Consumer interface can only accept one parameter, but can handle multiple parameters by customizing the interface, using Tuple or nested structure. For the Supplier interface, it cannot accept parameters, but it can realize the function of customizing BiSupplier, combining Function or encapsulating parameters as objects to achieve the function of two parameters and returning a value. The article introduces the use of Consumer and Supplier functional interfaces in Java, as well as how to implement similar functions of multi-parameters through custom interfaces, using combinations or third-party libraries.

How does Consumer accept multiple parameters?

In Java,ConsumerIs only acceptOne parameterThe functional interface is defined inIn the package. The main method isaccept(T t), used to process incoming parameters without returning values.

If you need one, you can accept itThree parametersSimilar functions can be implemented in the following ways:

1. Create a custom Consumer interface

You can define a 3-parametersConsumer

@FunctionalInterface
public interface TriConsumer<T, U, V> {
    void accept(T t, U u, V v);
}

Example of usage:

TriConsumer<String, Integer, Boolean> triConsumer = (name, age, isActive) -> {
    ("Name: " + name);
    ("Age: " + age);
    ("Active: " + isActive);
};

("Alice", 25, true);

2. Ready-made functional interface using three parameters

Although there is noTriConsumer, but similar functionality may be provided in some third-party libraries such as Apache Commons or Vavr. This way you don't need to implement it yourself.

3. Use combinationConsumersolve

If you insist on using Java's ownConsumer, three parameters can be packaged into one object and passed. For example:

useConsumerandTuple

class Tuple3<T, U, V> {
    final T first;
    final U second;
    final V third;

    public Tuple3(T first, U second, V third) {
         = first;
         = second;
         = third;
    }
}

Consumer<Tuple3<String, Integer, Boolean>> consumer = tuple -> {
    ("Name: " + );
    ("Age: " + );
    ("Active: " + );
};

(new Tuple3<>("Bob", 30, false));

4. useBiConsumerand nesting

BiConsumerIt is a functional interface that supports two parameters in the standard library. By nestingConsumer, can indirectly implement operations on three parameters:

BiConsumer<String, Integer> biConsumer = (name, age) -> {
    Consumer<Boolean> innerConsumer = isActive -> {
        ("Name: " + name);
        ("Age: " + age);
        ("Active: " + isActive);
    };
    (true);
};

("Charlie", 28);

Reference code

@Override
    public List&lt;CsAIAppConfig&gt; doGenerateDefaultAI(AIServiceSettingDTO aiServiceSetting) {
        List&lt;CsAIAppConfig&gt; aiConfigOfList = new ArrayList&lt;&gt;();

        // Define a common method to build and generate AI configuration        BiConsumer&lt;String, AIEnableEnum&gt; createAIConfig =
                (modelId, enableEnum) -&gt; (modelId).ifPresent(id -&gt; {
                    SaveOrUpdateAIEntity build = ()
                            .targetId("DEFAULT")
                            .modelId(id)
                            .aiEnableEnum(enableEnum)
                            .knowledge(getKnowledgeByEnum(enableEnum, aiServiceSetting))
                            .csAIAppConfigs(())
                            .build();
                    generateAI(build, aiConfigOfList);
                });

        // Build various AI configurations        ((), AIEnableEnum.CS_WORK_ORDER_AI_ENABLE);
        ((), AIEnableEnum.CS_WX_KF_AI_ENABLE);
        ((), AIEnableEnum.CS_ZX_KF_AI_ENABLE);
        ((), AIEnableEnum.CS_MH_KH_AI_ENABLE);

        return aiConfigOfList;
    }

How to accept two parameters in Supply?

In the Java standard library,Supplieris a functional interface that generates a result. Its core approach is:

T get();

This meansSupplierNo parameters are accepted, only responsible for returning one value.

If you need something likeSupplierAccept two parameters:

The Java standard library does not directly provide such an interface, but you can implement it in the following ways:

1. Customize a similarBiSupplierInterface

You can create an interface that supports two input parameters and returns a value:

@FunctionalInterface
public interface BiSupplier<T, U, R> {
    R get(T t, U u);
}

Example of usage:

BiSupplier&lt;String, Integer, String&gt; biSupplier = (name, age) -&gt; 
    "Name: " + name + ", Age: " + age;

(("Alice", 25)); // Output: Name: Alice, Age: 25

2. CombinedFunctionuse

If you don't want to create a new interface, you can useBiFunctionAlternative:

BiFunction&lt;String, Integer, String&gt; biFunction = (name, age) -&gt; 
    "Name: " + name + ", Age: " + age;

(("Alice", 25)); // Output: Name: Alice, Age: 25

Although its name isBiFunction, but functionally equivalent to one that accepts two parametersSupplier

3. Encapsulate parameters as objects

You can still use the standardSupplier

class Person {
    String name;
    int age;

    public Person(String name, int age) {
         = name;
         = age;
    }

    @Override
    public String toString() {
        return "Name: " + name + ", Age: " + age;
    }
}

Supplier&lt;Person&gt; personSupplier = () -&gt; new Person("Alice", 25);

(()); // Output: Name: Alice, Age: 25

Summarize

Java'sConsumerOnly one parameter can be accepted by itself. For three parameters, you can customize itTriConsumer,useTupleor nested structure. If more powerful functional interface support is needed, consider introducing third-party libraries or switching to a more advanced solution.

SupplierIt cannot accept any parameters itself and is only responsible for providing a value. If you need to accept two parameters and return a value: CustomBiSupplier. useBiFunctionAlternative. Encapsulate the parameters as an object, continue to use the standardSupplier

Here is the article about how to implement multi-parameters in Consumer and Supply in Java? That’s all for the article. For more related multi-parameter content in Consumer and Supply in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!