Java 使用带参数的方法引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29835382/
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
Use method reference with parameter
提问by matepal297
I just started learning Java streams and faced a problem. Please take a look at a the following example. This is part of a Node class:
我刚开始学习 Java 流并遇到了一个问题。请看下面的例子。这是 Node 类的一部分:
private Map<String, Node> nodes;
public Optional<Node> child(String name) {
return Optional.<Node>ofNullable(nodes.get(name));
}
private void findChildren(String name, List<Node> result) {
child(name).ifPresent(result::add);
nodes.values().stream()
// .map(Node::findChildren(name, result))
// .forEach(Node::findChildren(name, result))
.forEach(node -> node.findChildren(name, result));
}
My intent was to call #findChildren with the name and result parameters on each node in the stream. I tried to use the method references Node::findChildren with no luck. I'd appreciate solutions other the the one with ->
operator.
我的意图是在流中的每个节点上使用名称和结果参数调用 #findChildren。我尝试使用方法引用 Node::findChildren ,但没有运气。我很欣赏其他解决方案与->
运营商的解决方案。
Is it somehow possible to use the method reference together with a parameter? I like the idea of streams and I just want to make the code more readable.
是否可以将方法引用与参数一起使用?我喜欢流的想法,我只是想让代码更具可读性。
Actually, I think there is a similar question Method references with a parameterwhich I read but cannot figure out how to use the bind2 method in my code. Is it the only solution?
实际上,我认为有一个类似的问题Method references with a parameter我读过但无法弄清楚如何在我的代码中使用 bind2 方法。这是唯一的解决方案吗?
采纳答案by Holger
You can't use method references for this purpose. You have to resort to lambda expressions. The reason why the bind2
method of the linked question doesn't work is that you are actually trying to bind twoparameters to convert a three-arg function into a one-arg function. There is no similarly simple solution as there is no standard functional interface
for three-arg consumers.
您不能为此目的使用方法引用。您必须求助于 lambda 表达式。bind2
链接问题的方法不起作用的原因是您实际上是在尝试绑定两个参数以将三参数函数转换为一参数函数。没有类似的简单解决方案,因为interface
对于三参数消费者没有标准功能。
It would have to look like
它必须看起来像
interface ThreeConsumer<T, U, V> {
void accept(T t, U u, V v);
}
public static <T, U, V> Consumer<T> bind2and3(
ThreeConsumer<? super T, U, V> c, U arg2, V arg3) {
return (arg1) -> c.accept(arg1, arg2, arg3);
}
Then .forEach(bind2and3(Node::findChildren, name, result));
could work. But is this really simpler than .forEach(node -> node.findChildren(name, result));
?
然后.forEach(bind2and3(Node::findChildren, name, result));
就可以工作了。但这真的比 更简单.forEach(node -> node.findChildren(name, result));
吗?