Java 8:两个对象供应商

问题描述 投票:0回答:2

我有一个二元函数:

public Integer binaryFunction(Integer a, Integer b){
    //some stuff
}

我有这个流:

Integer fixedValue = ...
List<Integer> otherValues = ...
otherValues.map(value -> binaryFunction(value, fixedValue)).collect(...);

我想知道如何在我的直播中使用

map(this::binaryFunction)
。我尝试过类似的方法,但它不起作用:

values.map(value -> (value, fixedValue)).map(this::binaryFunction).collect(...);

但这不起作用。我正在寻找可以接受两个值的供应商。

注意:我不想更改

binaryFunction
声明。

谢谢!

java lambda java-stream
2个回答
4
投票

你不能这样做。您必须使用您显示的 lambda。

您可以编写一个修改二元函数的函数来修复其第一个参数,但其主体将是相同的 lambda。


0
投票

如果您将固定值作为类级别变量并且不需要在函数中提供它,那么您可以执行此操作的唯一方法。换句话说

public class Foo {
    private Integer fixedValue;


    public Integer binaryFunction(Integer a) {
        //use fixedValue (as it is class variable)
        //some stuff
    }

    public void doSomeThing() {
        this.fixedValue = ...//setting fixed value here
        List<Integer> otherValues = ...
        otherValues.map(this::binaryFunction)...
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.