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
Just call
Function.apply
.A
Function
is simply aninterface
that defines one method:Your
powerOfTwo
is simply an anonymousclass
that implements theFunction
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:Or, using the
int
version (so that you don't autobox toInteger
):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 theFunctions
utility class tocompose
multiple functions:With Java 8, due to default method the
Function
interface can actually offer vast amounts of functionality whilst still only having oneabstract
method. Therefore in Java 8 you can do:Or even: