Reputation: 372
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
Reputation: 61138
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