Sobes.tech
Middle

What are functional interfaces? Which ones do you know? What do they accept and what do they return?

sobes.tech AI

Answer from AI

Functional interfaces in Java are interfaces with a single abstract method, which can be used as target types for lambda expressions and method references.

Main functional interfaces from the java.util.function package:

  • Function<T, R> — takes an object of type T, returns an object of type R.
  • Consumer<T> — takes an object of type T, returns nothing (void).
  • Supplier<T> — takes no arguments, returns an object of type T.
  • Predicate<T> — takes an object of type T, returns a boolean.
  • UnaryOperator<T> — takes and returns an object of type T (a specialization of Function).
  • BinaryOperator<T> — takes two objects of type T, returns an object of type T.

Example of using Function:

Function<String, Integer> lengthFunc = s -> s.length();
int len = lengthFunc.apply("hello"); // 5

Thus, functional interfaces allow writing more concise and expressive code using lambdas.

What are functional interfaces? Which ones do you… - sobes.tech