You should be able to achieve what you want inline by using casts:
Stream.of("ciao", "hola", "hello")
.map(((Function<String, Integer>) String::length).andThen(n -> n * 2))
There are only 'type hints' for the compiler, so they don't actually 'cast' the object and don't have the overhead of an actual cast.
Alternatively, you can use a local variable for readability:
Function<String, Integer> fun = String::length
Stream.of("ciao", "hola", "hello")
.map(fun.andThen(n -> n * 2));
A third way that may be more concise is with a utility method:
public static <T, X, U> Function<T, U> chain(Function<T, X> fun1, Function<X, U> fun2)
{
return fun1.andThen(fun2);
}
Stream.of("ciao", "hola", "hello")
.map(chain(String::length, n -> n * 2));
Please note that this is not tested, thus I don't know if type inference works correctly in this case.
.map(s -> s.length() * 2)as there is no reason to express it as two functions just to combine them immediately. If you have an already existingFunctioninstance or want to keep at least one of them for later re-use, the problem does not exist as then you have an object you can invoke eitherandThenorcomposeon. In all other cases, there is no reason to do it that complicated.