Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining lambda functions [duplicate]

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);
like image 218
bvdb Avatar asked Sep 09 '15 21:09

bvdb


People also ask

How do you duplicate a lambda function?

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.

Can we reuse lambda expression?

Fortunately, you can assign lambda expressions to variables and reuse them, as you would with objects.


1 Answers

Java 8 Functions 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).

like image 146
Tunaki Avatar answered Oct 05 '22 16:10

Tunaki