The question is not stupid at all. Answering this in a broader sense: unfortunately, there is no general solution for this. This is due to the type of output, which defines one specific type for the lambda expression based on the target type. (The output type section may be useful here, but does not cover all the details regarding lambdas.)
In particular, such a lambda as x -> y does not exist. Thus, there is no way to write
GenericLambdaType function = x -> y;
and then use function as a replacement for the actual lambda x -> y .
For example, when you have two functions, such as
static void useF(Function<Integer, Boolean> f) { ... } static void useP(Predicate<Integer> p) { ... }
you can call them both with the same lambda
useF(x -> true); useP(x -> true);
but there is no way to "store" the lambda x -> true in such a way that it can later be passed to both functions , you can only store it in a link with the type that you will need later:
Function<Integer, Boolean> f = x -> true; Predicate<Integer> p = x -> true; useF(f); useP(p);
In your particular case, Konstantin Yovkov’s answer already showed a solution: you should save it as a Comparator<Integer> (ignoring the fact, I need the first lambda in the first place ...)
Marco13
source share