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).
I hope you don't mind if I don't use an Array
, but I will use your square
method
public Map<Integer, Integer> lotsOfSquares(int limit) {
return IntStream.rangeClosed(1,limit) // Creates a stream of 1, 2, 3, ... limit
.boxed() // Boxes int to Integer.
.collect(Collectors.toMap(i -> i, // Collects the numbers, i->i generates the map key
i -> square(i)); // Generates the map value
}
This will give you a map containing {1=1, 2=4, 3=9, ... , 99=9801, 100=10000}
.
You should probably add some validation on limit
.
Update:
public <T> Map<Integer, T> lotsOfResults(int limit, Function<Integer, T> f) {
return IntStream.rangeClosed(1,limit)
.boxed()
.collect(Collectors.toMap(i -> i,
i -> f.apply(i));
}
Now, you can call lotsOfResults(100, i -> square(i))
Note that T
is the return type of f
-- in case you get tired of squaring.
Hope this helps:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With