1

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?

7
  • I think you have two ways: - Write a fun with 1 param (num), then return Math.pow(num, 2), use that fun for method reference. - just use it*it for the square on map function without method reference. Commented Jul 2, 2020 at 6:57
  • You can't use a method reference here, just use a lambda instead. .mapToDouble(n -> Math.pow(n, 2)) Commented Jul 2, 2020 at 6:59
  • Method reference only work if the method has the same input param + return type with the main method of target functional interface (geeksforgeeks.org/functional-interfaces-java) Commented Jul 2, 2020 at 7:01
  • I mean, if you use Math.pow(num, 2) directly it can't be referenced, if you write another method that have 1 param and return a double, that method can be referenced in this case, I'll show you the code if needed. Commented Jul 2, 2020 at 7:03
  • Or are you talking about partial application? (which, in this instance, would be overkill) Commented Jul 2, 2020 at 7:09

3 Answers 3

3

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))
Sign up to request clarification or add additional context in comments.

2 Comments

Do you know how to pass in a method reference instead of using a lambda? I'm just wondering if it's possible, because I think it makes it look cleaner.
@Higigig no, it would not make the code cleaner. It would make it look different, that’s all.
1

You can use a simple lambda expression.

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

Comments

0

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);
    }
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.