4

Assume that I have a method A and B from a class:

List<String> A(int start, int size);
List<String> B(int start, int size);

Now, I have another function that might use A or B. But before invoking them, I'll do some logic first:

void C() {
 // lots of logic here
 invoke A or B
 // lots of logic here 
}

I want to pass method A or B as parameter of C, something like:

void C(Function<> function) {
 // lots of logic here
 invoke function (A or B)
 // lots of logic here 
}

However, I noticed that the Function class in Java can only accept one parameter (method A or B both have two parameters). Is there a workaround on this? (I don't want to change the method A or B signatures).

3
  • 5
    Sure. Use BiFunction. Commented Aug 1, 2018 at 23:40
  • Wow, thanks. BTW, what if method A and B has different return types (List<String> vs List<Integer>) ? Does this still work? Commented Aug 1, 2018 at 23:45
  • Use Lambdas. The only change would be function A and function B would be an implementation of an abstract function Commented Aug 1, 2018 at 23:45

2 Answers 2

4

BiFunction represents a function that accepts two arguments and produces a result, so you may want to look into that here.

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

2 Comments

Thanks, BTW, what if method A and B has different return types (List<String> vs List<Integer>) ? Does this still work?
@injoy try generalising your method to <T> void C(BiFunction<Integer, Integer, List<T>> function) {...}?
0

You can use and write your own functional interface by lambda expression. I illustrate here,

interface MyInterface<T> {
    List<T> f(int start, int size);
}

class Example {
    List<String> A(int start, int size) {
        return new ArrayList<String>();
    }

    List<Integer> B(int start, int size) {
        return new ArrayList<Integer>();
    }

    void C(MyInterface function) {

    }

    public static void main(String[] args) {
        Example e = new Example();
        MyInterface<String> methodForA = (x,y) -> e.A(1,2);
        MyInterface<Integer> methodForB = (x,y) -> e.B(1,2);

        e.C(methodForA);
        e.C(methodForB);
    }
}

2 Comments

Why not just use a method reference instead of a lambda?
@vandench I don't have enough knowledge yet about method references

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.