我有一个二元函数:
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
声明。
你不能这样做。您必须使用您显示的 lambda。
您可以编写一个修改二元函数的函数来修复其第一个参数,但其主体将是相同的 lambda。
如果您将固定值作为类级别变量并且不需要在函数中提供它,那么您可以执行此操作的唯一方法。换句话说
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)...
}
}
你可以做这样的事情。
Integer fixedValue = 8;
List<Integer> otherValues = List.of(10, 20, 30, 40);
Function<Integer, Integer> fnc = k -> binaryFunction(
k, fixedValue);
List<Integer> list = otherValues.stream().map(fnc).toList();
System.out.println(list);
打印
[18, 28, 38, 48]
public Integer binaryFunction(Integer a, Integer b) {
return a + b;
}
但我会选择你最初考虑的功能相同的东西。
List<Integer> list = otherValues.stream()
.map(val->binaryFunction(fixedValue, val)).toList();
通过 lambda 使用方法引用没有任何好处。查看 Brian Goetz 的 this 回答。