What functional interfaces do you know? Can you give examples?
sobes.tech AI
Answer from AI
In Java, functional interfaces are interfaces with a single abstract method that can be used with lambda expressions and method references.
Main examples from the java.util.function package:
-
Predicate<T> — takes an object of type T, returns boolean. Example: checking if a number is positive.
Predicate<Integer> isPositive = x -> x > 0; System.out.println(isPositive.test(5)); // true -
Function<T, R> — takes T, returns R. Example: converting a string to its length.
Function<String, Integer> length = s -> s.length(); System.out.println(length.apply("Hello")); // 5 -
Consumer<T> — takes T, returns nothing. Example: printing a string to the console.
Consumer<String> printer = s -> System.out.println(s); printer.accept("Hello"); -
Supplier<T> — takes no arguments, returns T. Example: generating a random number.
Supplier<Double> random = () -> Math.random(); System.out.println(random.get()); -
UnaryOperator<T> — takes and returns the same type T. Example: doubling a number.
UnaryOperator<Integer> doubler = x -> x * 2; System.out.println(doubler.apply(4)); // 8 -
BinaryOperator<T> — takes two arguments of type T and returns T. Example: sum of two numbers.
BinaryOperator<Integer> adder = (a, b) -> a + b; System.out.println(adder.apply(3, 7)); // 10
These interfaces are widely used for functional programming, collection processing, and streams.