Functional Interfaces in java
Functional Interface was introduced in java 8 to allow us to use lambda expression or method references to provide concise and readable code for functional programming. In functional programming, the function is an independent entity.To indicate an interface is a functional interface we can use @FunctionalInterface annotation.
A functional interface can contain only one abstract method, but it can also contain any number of static and default (non-abstract) methods. Abstract methods are those that do not require implementation during their declaration and must be overridden by the class implementing the interface.
Various built-in interfaces were declared with the @FunctionalInterface annotation and became functional starting from Java 8. While the annotation is not strictly required, it is good practice to use it because it can help the compiler provide assistance in case we accidentally add multiple abstract methods to the interface.
Here's an example of a functional interface:
@FunctionalInterface
interface MyFunctionalInterface {
void doSomething(); // This is the single abstract method
}
Two Ways to Use Functional Interfaces in a Class:
1)Using Lambda Expression
MyFunctionalInterface funcInterface = () -> {
// Implementation of the doSomething method
System.out.println("Doing something...");
};
funcInterface.doSomething(); // Calls the doSomething method
2)By Implementing the Interface
class MyClass {
static void myStaticMethod() {
System.out.println("Static method called.");
}
}
MyFunctionalInterface funcInterface = MyClass::myStaticMethod;
funcInterface.doSomething(); // Calls the myStaticMethod
Functional interfaces are of 4 types, Function, Consumer, Predicate, and Supplier.
1) Function: Represents a function that takes one argument and produces a result.It has a single abstract method called apply(). The apply() method takes one argument of type T and returns a result of type R.
Function<Integer, Integer> square = x -> x * x;
int result = square.apply(5); // Result will be 25
2) Predicate - Represents a boolean-valued function. Methods present are
1. test(T t),
领英推荐
2. isEqual(Object t),
3. and (Predicate P),
4. or(Predicate P),
5. negate()
Predicate<Integer> isEven = x -> x % 2 == 0;
boolean even = isEven.test(6); // Result will be true
3) Consumer - Represents an operation that takes an argument and returns no result. Methods present are :
Consumer<String> printMessage = message -> System.out.println(message);
printMessage.accept("Hello, world!"); // Prints "Hello, world!"
4) Supplier - Represents a supplier of results. Method present is : get()
Supplier<Double> randomValue = () -> Math.random();
double value = randomValue.get(); // Returns a random double value
Some built-in interfaces are as follows-