2.2.  Develop code that uses the Function interface

[Note]

A java.util.function.Function is a Java 8 functional interface whose sole purpose is to return any result by working on a single input argument. It accepts an argument of type T and returns a result of type R, by applying specified logic on the input via the apply method. The interface definition shown here:


package java.util.function;

@FunctionalInterface
public interface Function<T extends Object, R extends Object> {

    public R apply(T t);

    ...

}

					

A Function interface is used in cases when you want to encapsulate some code into a method which accepts some value as an input parameter and then returns another value after performing required operations on the input. The input parameter type and the return type of the method can either be same or different:


Function<String, Boolean> f = s -> new Boolean(s);

System.out.println(f.apply("TRUE"));
System.out.println(f.apply("true"));
System.out.println(f.apply("Java8"));
System.out.println(f.apply(null));

					

Output:

true
true
false
false
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Exam 1Z0-810: Upgrade to Java SE 8 Programmer Quiz