2

Sometime I need to make callback from one method to another:

final Integer i = 5;
final Integer j = 10;
foo("arg1", "arg2", (x, y) -> { 
    /** do sth which need this context **/ 
    bar(i + x, j - y);
})

But in such case I need to write simple interface (somewhere):

public interface someName {
    void noMatterName(Integer a, Integer c);
}

Then function foo() can call noMatterName - this is ok. But in simple cases, name of such interfaces and its function is not important. I just want to use lambda with two parameters.

Question:

Do I need to create this interface manually even if I need to make such "communication" between only two function? Does Java provide any similar interface? Or even something like this:

public interface someName1 {
    void noMatterName(Object a);
}

public interface someName2 {
    void noMatterName(Object a, Object b);
}

1 Answer 1

5

You can use the Consumer<T> (if you need a single parameter), and BiConsumer<T,U> (if you need 2 parameters) functional interfaces.

Interface Consumer<T>

Represents an operation that accepts a single input argument and returns no result.

Interface BiConsumer<T,U>

Represents an operation that accepts two input arguments and returns no result.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.