Arseny Istlentyev
Arseny Istlentyev

Reputation: 449

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?

Upvotes: 2

Views: 1235

Answers (2)

Stephen Roebuck
Stephen Roebuck

Reputation: 69

Perhaps you should look into the andThen() composition methods of the Function interface.

For example, something like this:

Function<Double, Double> f1 = (x) -> 3 * x; Function<Double, Double> f2 = (x) -> Math.pow(x, 2); Double x = 100d; Double result = f1.andThen(f2).apply(x);

outputs:

90000.0

or if you want to reverse the order (apply the Math.pow() first, then multiply by three):

Double result = f2.andThen(f1).apply(x);

outputs:

30000.0

and that works just as well.

the andThen() method allows you to "chain" your functions together. Provided that the output type of f1 matches the input type of f2, you're all set. You can continue chaining as far as you want, as the andThen() method actually returns a new Function<> object.

Upvotes: 0

Tunaki
Tunaki

Reputation: 137184

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.

Upvotes: 3

Related Questions