我试图使用java 8的流来计算使用前两个值的值的乘法.我想调用一个返回数组/列表/集合的函数.我正在创建一个List并向其添加1,2.
假设列表名称是结果.
public static void main (String[] args) {
List<Integer> result = new ArrayList<Integer>();
result.add(1);
result.add(2);
int n = 5; //n can be anything, choosing 5 for this example
res(n, result);
//print result which should be [1, 2, 2, 4, 8]
}
public static List<Integer> res(int n, List<Integer> result ) {
result.stream()
.limit(n)
.reduce(identity, (base,index) -> base);
//return result;
}
Run Code Online (Sandbox Code Playgroud)
现在问题是尝试将结果传递到流中以使用流继续使用新值更新列表.根据java教程,尽管效率低下,但它是可能的.
"如果你的reduce操作涉及向集合添加元素,那么每次你的累加器函数处理一个元素时,它都会创建一个包含该元素的新集合,这是低效的."
我是否需要使用可选的第三个参数BinaryOperator组合来组合列表+结果?
<U> U reduce(U identity,
BiFunction<U,? super T,U> accumulator,
BinaryOperator<U> combiner)
Run Code Online (Sandbox Code Playgroud)
简而言之; 我想传递一个包含两个值的列表,并让函数找到前两个值的乘法(1,2),将其添加到列表中,并找到最后两个值的乘法(2,2),并添加它到列表中,直到流达到限制.
我试图像这样对一组计算进行基准测试 -
def benchmark(func, index, array)
start = Time.now
func(index, array)
start - Time.now #returns time taken to perform func
end
def func1(index, array)
#perform computations based on index and array
end
def func2(index, array)
#more computations....
end
benchmark(func1, index1, array1)
benchmark(func1, index2, array2)
Run Code Online (Sandbox Code Playgroud)
现在我想知道如何实现这一目标.我试过这个例子,但是吐了出来
`func1': wrong number of arguments (0 for 2) (ArgumentError)
Run Code Online (Sandbox Code Playgroud)
如果我尝试 -
benchmark(func1(index1, array1), index1, array1)
Run Code Online (Sandbox Code Playgroud)
吐出来......
undefined method `func' for main:Object (NoMethodError)
Run Code Online (Sandbox Code Playgroud)
我看到了一个类似的问题,但它是为了python.使用参数将函数传递给Python中的另一个函数? 有人可以帮忙吗?谢谢.