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
Functionis simply aninterfacethat defines one method:Your
powerOfTwois simply an anonymousclassthat implements theFunctioninterface.The same is true for
Predicate.Note, that in Java 8, there is a whole host of
Functiontypes and with lambdas your code becomes:Or, using the
intversion (so that you don't autobox toInteger):You ask can i chain as well ?. The answer is in Java 7, no. Because the Guava
Functioninterfacedefines only one method there is no way it can provide that functionality. You need to use theFunctionsutility class tocomposemultiple functions:With Java 8, due to default method the
Functioninterface can actually offer vast amounts of functionality whilst still only having oneabstractmethod. Therefore in Java 8 you can do:Or even: