Search code examples
javagenericsjava-8functional-interface

is it possible to pass a function with 2 parameters as parameter for another function in java 8/11?


I have this problem.

I am working with some generics and at one point I will need a specific converted depending on each type.

So, so far I have this:

public static <T> List<T> myMethod(List<T> list1, List2<T>, SomeFunction converter) { 
//... do suff
return converter.convert(list1, list2);

}

and converter would be like this:

public <T> List<T> converter(List<T> list1, List<T> list2) {
/// cast and do stuff)
return List<T> some stuff;
}

Then I would like to make a call like

myMethod<list1,list2,converter);

I know about the functional internface Function but I need to send two parameters for this, is there any way I could do it in Java8/11?

Ideas?


Solution

  • Look into BinaryOperator which represents an operation upon two operands of the same type, producing a result of the same type as the operands.

    public static <T> List<T> someMethodName(List<T> list1, List<T> list2,  
                 BinaryOperator<List<T>> converter) { 
        return converter.apply(list1, list2);
    }
    

    BiFunction is also another option as it represents a function that accepts two arguments and produces a result.

    public static <T, R> List<R> someMethodName(List<T> list1, List<T> list2,
                BiFunction<List<T>, List<T>, List<R>> converter) {
        return converter.apply(list1, list2);
    }
    

    To call the function let's assume you have two Integer lists for example sakes:

    List<Integer> first = ....
    List<Integer> second = ....
    

    and you wanted to concatenate them, you'd pass both lists and a behaviour e.g.

    List<Integer> concat = someMethodName(first, second, 
                           (l, r) -> Stream.concat(l.stream(), r.stream())
                           .collect(Collectors.toList()));