Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java stream - flatmap with method reference

I am new to java and to stream so my question is why does this work:

This method is in my Tree class:

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

flatMap wants a function with t as param and flattened method doesnt have input parameters at all

whats happening here?

like image 853
Joey Avatar asked Feb 04 '23 22:02

Joey


1 Answers

There is indeed a hidden parameter in your function call. Because flattened is a non-static method, there is an implicit parameter in your function, which is known as this.

Basically, you are calling flattened on each object in your stream, with the said element being your parameter.

EDIT (for clarification): Tree::flattened can mean one of two things. It could mean:

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

or it could also mean:

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

further to that, it could also mean:

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

From the 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

like image 130
Joe C Avatar answered Feb 07 '23 17:02

Joe C