Higigig
Higigig

Reputation: 1275

How To Pass A Method Reference With Parameter In Java?

I don't know the exact name for it (I'm guessing method-reference) but here is what I'm talking about. Let's say I want to take the square root of all doubles in a double array. Then, if the array is called arr, I can do this:

Arrays.stream(arr).map(Math::sqrt). // ... box it and stuff

However, if I want to square each number in an int array, I'm thinking of using Math.pow(num, 2) as the method. However, Math.pow has a second parameter, but I know it will always be 2. So I'm thinking I can do something like this:

Arrays.stream(arr).map(Math::pow(2)). // ... box it and stuff

But this results in an error. What can I do?

Upvotes: 1

Views: 1699

Answers (3)

Phong Nguyen
Phong Nguyen

Reputation: 7117

There are 2 ways to implement this:

  • First, use lambda expression:

    Arrays.stream(arr).map(num -> Math.pow(num, 2));
    
  • Second, (if you still want to invoke a method reference here, and to understand correctly how method reference works): write another method that call Math.pow():

    Arrays.stream(arr).map(this::square);
    
    
    private double square(double num) {
        return Math.pow(num, 2);
    }
    

Upvotes: 0

Federico klez Culloca
Federico klez Culloca

Reputation: 27159

You can use a simple lambda expression.

Arrays.stream(arr).map(d -> Math.pow(d, 2));

Upvotes: 1

Amit Dony
Amit Dony

Reputation: 31

you may use lambda and send Math.pow(n,2)

like this:

Stream.of(1.1,1.2,1.3).map(n -> Math.pow(n,2))

Upvotes: 3

Related Questions