有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带方法引用的java流平面图

我是java和stream的新手,所以我的问题是为什么会这样做:

此方法位于myTree类中:

public Stream<Tree> flattened() {
    return Stream.concat(
            Stream.of(this),
            children.stream().flatMap(Tree::flattened));
}

flatMap需要一个参数为t的函数,而flatMap方法根本没有输入参数

这里发生了什么事


共 (1) 个答案

  1. # 1 楼答案

    函数调用中确实有一个隐藏参数。因为flattened是一个非静态方法,所以函数中有一个隐式参数,称为this

    基本上,您正在流中的每个对象上调用flattened,所述元素是您的参数

    编辑(为了澄清):Tree::flattened可以指两件事之一。这可能意味着:

    tree -> Tree.flattened(tree) //flattened is a static method, which yours is not
    

    也可能意味着:

    tree -> tree.flattened() //flattened is an instance method, as in your case
    

    除此之外,它还可能意味着:

    tree -> this.flattened(tree) //also doesn't apply to your case
    

    JLS开始:

    If the compile-time declaration is an instance method, then the target reference is the first formal parameter of the invocation method. Otherwise, there is no target reference