Can you list and explain the main functional interfaces used in Java?
sobes.tech AI
Answer from AI
In Java, functional interfaces are interfaces with a single abstract method that can be used in lambda expressions and method references.
Main functional interfaces from the java.util.function package:
-
Function<T, R> — takes an object of type T and returns an object of type R.
Function<String, Integer> lengthFunc = s -> s.length(); int len = lengthFunc.apply("Hello"); // 5 -
Consumer<T> — takes an object of type T and returns nothing (performs an action).
Consumer<String> printer = s -> System.out.println(s); printer.accept("Hello"); -
Supplier<T> — takes no arguments and returns an object of type T.
Supplier<Double> randomSupplier = () -> Math.random(); double val = randomSupplier.get(); -
Predicate<T> — takes an object of type T and returns a boolean.
Predicate<String> isEmpty = s -> s.isEmpty(); boolean result = isEmpty.test(""); // true -
UnaryOperator<T> — extends Function, takes and returns an object of the same type T.
-
BinaryOperator<T> — takes two objects of type T and returns an object of type T.
These interfaces allow writing concise and expressive code, especially when working with streams and collections.