Skip to content
Advertisement

java8 possibility to apply mathematical operators to functions

Assume, I’ve got two functions.

Function<Double, Double> function1 = (x) -> (3*x);
Function<Double, Double> function2 = (x) -> (Math.pow(x, 2));

I want to multiply these functions. So I want to get this lambda expression as a result:

(x) -> (3*Math.pow(x,3));

Is it possible in Java 8?

Advertisement

Answer

No, you won’t be able to do that with Function.

Suppose you have a Function.multiply(other) method, what would be the result of performing multiplication with the two following functions?

Function<String, String> f1 = s -> s.substring(1);
Function<String, Integer> f2 = s -> s.length();

However, if you rewrite your functions with DoubleUnaryOperator (or Function<Double, Double>), then you could have the following:

DoubleUnaryOperator f1 = x -> 3*x;
DoubleUnaryOperator f2 = x -> Math.pow(x, 2);

DoubleUnaryOperator f1xf2 = x -> f1.applyAsDouble(x) * f2.applyAsDouble(x);

The difference here is that we know that the operand of the function is a double and that it returns a double.

The f1xf2 function returns the multiplication of the result of f1 and f2. Since we know that both operands are double, the multiplication can be done safely.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement