Execute a method that generates the x and y values ​​of another given function

I was just starting to learn Java Runnable , and I heard about Callable s. However, I am very struggling with this problem. I would like to make a method that takes a function as an argument (be it Callable , a Runnable or something else, if I can just call the function like coolNewFunction(() -> otherFunction(), 100) or some other simple way) and the method will return an array of otherFunction return values. For example, let's say I defined a function

 public static int square(int x){ return x * x; } 

Then I could do something line by line:

 coolNewFunction(() -> square(), 100) 

And this will return an array of the first 100 numbers and their squares (ie {{1, 1}, {2, 4}, {3, 9}...} ). Now, from the very beginning, I know that lambda () -> square() will not work, because square must be passed a value. I want to create an array of 100 Runnable , each of which has the following argument for square , but the run() method does not return anything. So, a long story, what would a method look like that evaluates another function that is given as an argument of type square for different values ​​of x and returns an array of this estimate? In addition, it is advisable that I do not want to start any new topics, although if this is the only way to achieve this, but this is normal. Finally, I do not want to use the special function square (or another) (preferred).

+5
source share
2 answers

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; } 
+1
source

Hope you don't mind if I don't use 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 check 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 are tired of squaring.

+2
source

All Articles