Java Functional Interfaces
This section describes the concept of Functional Interfaces introduced in Java 8.
Introduction
Example:
public interface MyFirstFunctionalInterface {
void test1();
}
@FunctionalInterface Annotation
Examples:
@FunctionalInterface
public interface MyFirstFunctionalInterface {
void test1();
void test2(); //error
}
Error: No abstract method declared
@FunctionalInterface
public interface Foo {
static void foo() {
System.out.println(“Foo.foo”);
}
default void fooBar() {
System.out.println(“Foo.fooBar”);
}
}
@FunctionalInterface
@FunctionalInterface
public interface Foo {
static void foo() {
System.out.println(“Foo.foo”);
}
static void bar() {
System.out.println(“Foo.bar”);
}
default void fooBar() {
System.out.println(“Foo.fooBar”);
}
default void barFoo() {
System.out.println(“Foo.barFoo”);
}
}
}
}
Built-in Functional Interfaces
Java provides some built-in functional interfaces that are defined in java.util.Function package.
public interface Function<T,R>
{
R apply(T t);
}
Example:
This implementation of Function interface returns the Integer length of the String value passed as argument.
Function<String, Integer> myFunc = str -> str.length();
Integer len = myFunc.apply(“MyFirstFunction”); //15
public interface Predicate
{
boolean test(T t);
}
Example:
This implementation of Predicate interface tests the value passed as argument and returns true and false based on its nullity.
Predicate isNull = (value) -> value!=null;
public interface BinaryOperator
{
T apply(T x, T y);
}
Example:
This implementation of BinaryOperator interface returns the sum of two values passed as arguments.
BinaryOperator<AddNum> binaryOp = (num1, num2) ->
{ num1.add(num2);
return num1;
};
public interface UnaryOperator
{
T apply(T t);
}
Example:
This implementation of UnaryOperator interface modifies the object passed as argument and returns it.
UnaryOperator<Employee> unaryOp = (employee) ->
{ employee.phone = 9999999999;
return employee;
};
public interface Supplier<T>
{
T get();
}
Example:
This implementation of Supplier interface returns a new Integer instance with a random value.
Supplier<Integer> supplier = () -> new Integer((int) Math.random());
public interface Consumer<T>
{
void accept(T t);
}
Example:
This implementation of Consumer interface prints the value passed as argument.
Consumer<String> consumer = (value) -> System.out.println(value);
Leave a Reply