簡體   English   中英

如何將帶有參數的方法引用傳遞到Arrays.stream中?

[英]How to pass method references with parameters into Arrays.stream?

我有一個來自接口的方法,該方法通過一系列項和buff並計算所有特定方法的總和,如下所示:

@Override
public float getDamageReduction(EntityPlayable playable) {
    float bonus = (float) Arrays.stream(items).filter(Objects::nonNull).mapToDouble(Item::getDamageReduction(this)).sum();
    float buffBonus = (float)buffs.stream().mapToDouble(Buff::getDamageReduction(this)).sum();
    return bonus + buffBonus;
}

該代碼不起作用,因為您無法使用Buff::getDamageReduction(this)因為您不允許將方法引用與參數一起使用。

我該如何解決?

在這種情況下,您不能使用方法引用。 您可以改為編寫lambda表達式。

float bonus = (float) Arrays.stream(items)
                            .filter(Objects::nonNull)
                            .mapToDouble(item -> item.getDamageReduction(this))
                            .sum();

您不能以這種方式使用函數引用。 您可以通過以下方式在流外部創建Function

Function<Item, Double> func1 = item -> item.getDamageReduction(this);

和分別為第二行

Function<Buff, Double> func2 = buff -> buff.getDamageReduction(this);

然后按如下方式使用它:

float bonus = (float)Arrays.stream(items)
    .filter(Objects::nonNull)
    .mapToDouble(func1)
    .sum();

但我認為編寫起來要簡單得多:

float bonus = (float)Arrays.stream(items)
    .filter(Objects::nonNull)
    .mapToDouble(item -> item.getDamageReduction(this))
    .sum();

暫無
暫無

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

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