I have just started to learn about Java Runnable
s and I have heard of Callable
s. However, I am very much struggling with this problem. I would like to make a method which takes a function as an argument (whether that be as a Callable
, a Runnable
, or something else, as long as I can simply call the function as coolNewFunction(() -> otherFunction(), 100)
or some similar simple way) and the method would return an array of the returned values of the otherFunction
. For example, say I defined the function
public static int square(int x){
return x * x;
}
I could then do something along the lines of:
coolNewFunction(() -> square(), 100)
And this would return an array of the first 100 numbers and their squares (i.e. {{1, 1}, {2, 4}, {3, 9}...}
). Now right off the bat I know that the lambda () -> square()
wouldn't work because square
has to be passed a value. I though of creating an array of 100 Runnable
s each of which has the next argument for square
, but still the method run()
doesn't return anything. So, long story short, what would a method look like which evaluates another function which is given as an argument like square
at different x values and returns an array of that evaluation? Also, preferably I don't want to start any new threads although if this is the only way that this can be achieved than that is okay. Finally, I don't want to have to implement the square
(or other) function in a special way (preferably).