java 链接 lambda 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32489316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:16:39  来源:igfitidea点击:

Chaining lambda functions

javalambdajava-8java-stream

提问by bvdb

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.

当 Java 方法接受 a 时Function<? super T, ? extends U>,可以使用如下语法提供方法引用: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:

我想知道是否有将其转换为 lambda 表达式的语法。我希望有如下内容:

// 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);

采纳答案by Tunaki

Java 8 Functions can be chained with the method andThen:

Java 8Function可以使用以下方法链接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::trimdoes not compile because the trimmethod does not take any input, so it does not conform to the functional interface Function(same goes for String::toUpperCase).

请注意,在您的实际示例中,String::trim不会编译,因为该trim方法不接受任何输入,因此它不符合功能接口Function(同样适用于String::toUpperCase)。