制作一个生成另一个给定函数的x和y值的方法

Dyl*_*ler 5 java lambda callable runnable java-8

我刚刚开始学习Java Runnable,我听说过Callables.但是,我非常努力解决这个问题.我想创建一个方法,它将一个函数作为参数(无论是作为a Callable,a Runnable还是其他东西,只要我可以简单地调用函数coolNewFunction(() -> otherFunction(), 100)或类似的简单方法)并且该方法将返回一个数组返回值的otherFunction.例如,假设我定义了该函数

public static int square(int x){

    return x * x;

} 
Run Code Online (Sandbox Code Playgroud)

然后我可以做一些事情:

coolNewFunction(() -> square(), 100)
Run Code Online (Sandbox Code Playgroud)

这将返回前100个数字及其正方形(即{{1, 1}, {2, 4}, {3, 9}...})的数组.现在,我知道这lambda () -> square()不会起作用,因为square必须传递一个值.我虽然创建了一个100 Runnable秒的数组,每个数组都有下一个参数square,但该方法仍然run()没有返回任何内容.所以,长话短说,一个方法会是什么样的,它会评估另一个函数,它作为一个参数给出,就像square在不同的x值一样,并返回一个该评估的数组?此外,我最好不要开始任何新的线程,虽然这是唯一可以实现这一点的方法.最后,我不想以square特殊方式(最好)实现(或其他)功能.

d_s*_*ell 1

希望这可以帮助:

public int[][] fn2Array(Function<Integer, Integer> fn, int x) {
    int[][] result = new int[x][2];
    for (int i; i < x; i++) {
        result[i][0]=i+1;
        result[i][1]=fn.apply(i+1);
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

  • 考虑 `IntUnaryOperator` 而不是 `Function&lt;Integer, Integer&gt;`,它可以避免不必要的装箱。 (2认同)