When a Java method accepts a Function<? super T, ? extends U>
, then it's possible to provide method references in a syntax like the following: MyClass::myMethod
.
However, I'm wondering if there's a way to chain multiple method calls. Here's an example to illustrate the case.
// on a specific object, without lambda
myString.trim().toUpperCase()
I am wondering if there is a syntax to translate this to a lambda expression. I am hoping there is something like the following:
// something like: (which doesn't work)
String::trim::toUpperCase
Alternatively, is there a utility class to merge functions?
// example: (which does not exist)
FunctionUtil.chain(String::trim, String::toUpperCase);
There is no provided function to copy/clone Lambda Functions and API Gateway configurations. You will need to create new a new function from scratch. If you envision having to duplicate functions in the future, it may be worthwhile to use AWS CloudFormation to create your Lambda Functions.
Fortunately, you can assign lambda expressions to variables and reuse them, as you would with objects.
Java 8 Function
s can be chained with the method andThen
:
UnaryOperator<String> trimFunction = String::trim;
UnaryOperator<String> toUpperCaseFunction = String::toUpperCase;
Stream.of(" a ", " b ").map(trimFunction.andThen(toUpperCaseFunction)) // Stream is now ["A", "B"]
Note that in your actual example, String::trim
does not compile because the trim
method does not take any input, so it does not conform to the functional interface Function
(same goes for String::toUpperCase
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With