Chain lambda functions

When does the Java method accept Function<? super T, ? extends U> Function<? super T, ? extends U> Function<? super T, ? extends U> , then you can provide method references in the syntax, as shown below: MyClass::myMethod .

However, I am wondering if there is a way to link multiple method calls. Here is an example illustrating the case.

 // on a specific object, without lambda myString.trim().toUpperCase() 

I am wondering if there is syntax for translating this expression into lambda. I hope there is something like the following:

 // something like: (which doesn't work) String::trim::toUpperCase 

Alternatively, is there a utility class for combining functions?

 // example: (which does not exist) FunctionUtil.chain(String::trim, String::toUpperCase); 
+8
java lambda java-8 java-stream
source share
1 answer

Java 8 Function can be bound using the andThen method:

 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 accept any input, therefore it does not correspond to the Function functional interface (the same applies to String::toUpperCase ).

+5
source share

All Articles