Java provides predefined functional interfaces to deal with functional programming by using lambda and method references.
package com.java.session.seventeen;
@FunctionalInterface
public interface FunctionalInterfaceDemo {
int additionOfTwoNumber(int value1, int value2);
}
package com.java.session.seventeen;
public class FunctionalInterfaceExample {
public static void main(String[] args) {
FunctionalInterfaceDemo functionalInterfaceDemo = (v1, v2) -> v1 + v2;
int result = functionalInterfaceDemo.additionOfTwoNumber(10, 50);
System.out.println(result);
}
}
Before Java 8, interfaces could have only abstract methods. The implementation of these methods has to be provided in a separate class. So, if a new method is to be added in an interface, then its implementation code has to be provided in the class implementing the same interface. To overcome this issue, Java 8 has introduced the concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface.
Default methods only allow to use inside the interfaces, default is a keyword which is used to declare to a method. If a method delcare with the keyword default then we call it as a default method.
package com.java.session.seventeen;
@FunctionalInterface
public interface FunctionalInterfaceDemo {
int additionOfTwoNumber(int value1, int value2);
default String printResult(int result) {
return "Result is - "+result;
}
}
package com.java.session.seventeen;
public class FunctionalInterfaceExample {
public static void main(String[] args) {
FunctionalInterfaceDemo functionalInterfaceDemo = (v1, v2) -> v1 + v2;
int res = functionalInterfaceDemo.additionOfTwoNumber(10, 50);
System.out.println(res);
String finalResult = functionalInterfaceDemo.printResult(res);
System.out.println(finalResult);
}
}
1. Supplier<T>:
//Generates a random integer between 0 and 99
Supplier<Integer> randomNumberSupplier = () -> (int) (Math.random() * 100);
int randomValue = randomNumberSupplier.get();
// Prints "Hello, World!"
Consumer<String> printMessage = message -> System.out.println(message);
printMessage.accept("Hello, World!");
// "Number: 42"
Function<Integer, String> intToString = num -> "Number: " + num;
String result = intToString.apply(42);
// true
Predicate<Integer> isEven = num -> num % 2 == 0;
boolean result = isEven.test(8);