使用带参数的方法引用 [英] Use method reference with parameter

查看:252
本文介绍了使用带参数的方法引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习Java流并遇到了问题。请看下面的例子。这是Node类的一部分:

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:

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

我的意图是在每个节点上使用名称和结果参数调用#findChildren在溪流中。我试图使用方法引用Node :: findChildren没有运气。我很感激其他解决方案 - > 运营商。

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.

是否有可能使用方法参考和参数?我喜欢流的想法,我只是想让代码更具可读性。

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.

实际上,我认为存在类似的问题使用参数的方法引用,我读过但无法弄清楚如何在我的代码中使用bind2方法。它是唯一的解决方案吗?

Actually, I think there is a similar question Method references with a parameter which I read but cannot figure out how to use the bind2 method in my code. Is it the only solution?

推荐答案

您不能为此目的使用方法引用。你必须求助于lambda表达式。链接问题的 bind2 方法不起作用的原因是您实际上尝试绑定两个参数来转换三个arg函数转换为单参数函数。没有类似的简单解决方案,因为没有标准的功能接口三个arg消费者。

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 two parameters 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.

它会有看起来像

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

然后 .forEach(bind2and3(Node :: findChildren) ,名称,结果)); 可以工作。但这是否比 .forEach(node - > node.findChildren(name,result))更简单;

Then .forEach(bind2and3(Node::findChildren, name, result)); could work. But is this really simpler than .forEach(node -> node.findChildren(name, result));?

这篇关于使用带参数的方法引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆