Functional Interfaces
Learn about Functional Interfaces and predefined interfaces in java.util.function package.
Learn about Functional Interfaces and predefined interfaces in java.util.function package. This hands-on tutorial focuses on practical implementation of functional interfaces concepts.
Functional Interfaces
A Functional Interface is an interface with exactly one abstract method.
@FunctionalInterface Annotation
Ensures the interface has only one abstract method.
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}
Predefined Functional Interfaces
Java 8 provides many built-in functional interfaces in java.util.function.
1. Predicate<T>
Takes an argument, returns boolean.
Predicate<String> isValid = s -> s.length() > 5;
System.out.println(isValid.test("Hello World")); // true
2. Function<T, R>
Takes argument T, returns result R.
Function<String, Integer> getLength = s -> s.length();
System.out.println(getLength.apply("Java")); // 4
3. Consumer<T>
Takes argument T, returns void (consumes it).
Consumer<String> printer = s -> System.out.println(s);
printer.accept("Hello");
4. Supplier<T>
Takes no argument, returns result T (supplies it).
Supplier<Double> random = () -> Math.random();
System.out.println(random.get());
5. UnaryOperator<T> & BinaryOperator<T>
Specialized versions of Function where input/output types are same.
UnaryOperator<Integer> square = x -> x * x;
BinaryOperator<Integer> add = (a, b) -> a + b;
AI Mentor
AssistantConfused about "Java functional interfaces and java.util.function package"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 3How many abstract methods can a @FunctionalInterface have?