簡體   English   中英

java stream - 帶方法引用的flatmap

[英]java stream - flatmap with method reference

我是java的新手,所以我的問題是為什么這個工作:

這個方法在我的Tree類中:

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

flatMap想要一個帶有t作為param的函數,而flattened方法根本沒有輸入參數

這里發生了什么事?

函數調用中確實存在隱藏參數。 因為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

如果編譯時聲明是實例方法,則目標引用是調用方法的第一個形式參數。 否則,沒有目標參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM