Moshe Tsabari
Moshe Tsabari

Reputation: 372

Function Guava apply Function on Single object

It seems like very easy but I didn't found an explanation of how to apply a Function form guava api on single object

for example I have the following function

Function<Integer, Integer> powerOfTwo = new Function<Integer, Integer>() {
    @Override
    public Integer apply(Integer input) {
        return (int) Math.pow(input, 2);
    }
};

And I want to apply it on

Integer i = 6;

How do I do it

Same on predicate how can I Predicate on single object

Upvotes: 0

Views: 1628

Answers (1)

Boris the Spider
Boris the Spider

Reputation: 61138

Just call Function.apply.

final int applied = powerOfTwo.apply(i);

A Function is simply an interface that defines one method:

T apply(F input)

Your powerOfTwo is simply an anonymous class that implements the Function interface.

The same is true for Predicate.

Note, that in Java 8, there is a whole host of Function types and with lambdas your code becomes:

Function<Integer, Integer> powerOfTwo = i -> i * i;

Or, using the int version (so that you don't autobox to Integer):

IntFunction powerOfTwo = i -> i * i;

You ask can i chain as well ?. The answer is in Java 7, no. Because the Guava Function interface defines only one method there is no way it can provide that functionality. You need to use the Functions utility class to compose multiple functions:

Function<Integer, Integer> composed = Functions.compose(powerOfTwo, powerOfTwo);

With Java 8, due to default method the Function interface can actually offer vast amounts of functionality whilst still only having one abstract method. Therefore in Java 8 you can do:

Function<Integer, Integer> composed = powerOfTwo.compose(powerOfTwo);

Or even:

Function<Integer, Integer> composed = powerOfTwo.compose(i -> i + 2);

Upvotes: 3

Related Questions