Dylan Siegler Dylan Siegler - 1 year ago 70
Java Question

Make a Method Which Generates the x and y values of Another Given Function

I have just started to learn about Java

s and I have heard of
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
, a
, 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
. 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
has to be passed a value. I though of creating an array of 100
s each of which has the next argument for
, but still the method
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
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
(or other) function in a special way (preferably).

Answer Source

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.


public <T> Map<Integer, T> lotsOfResults(int limit, Function<Integer, T> f) {

    return IntStream.rangeClosed(1,limit)                        
                    .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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download