Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Java 8 FAQ: Top Questions

11. What are the different types of functional interfaces provided by Java 8?

Java 8 provides several built-in functional interfaces in the java.util.function package. These interfaces represent common operations such as consuming, transforming, supplying, and testing values.

πŸ—ΊοΈ Step-by-Step Overview:

  1. Predicate<T>: Tests a value and returns a boolean.
  2. Function<T, R>: Takes a value of type T and returns a value of type R.
  3. Consumer<T>: Takes a value of type T and returns nothing.
  4. Supplier<T>: Supplies a value of type T with no input.
  5. UnaryOperator<T>: A Function where input and output types are the same.
  6. BinaryOperator<T>: Takes two inputs of type T and returns a result of type T.

πŸ“₯ Example Input:

Predicate isLong = str -> str.length() > 5;
Function intToStr = i -> "Value: " + i;
Consumer printer = s -> System.out.println(s);
Supplier random = () -> Math.random();

πŸ† Expected Output:

true
Value: 10
[Printed String]
[Random Number]

βœ… Java 8 Solution:

import java.util.function.*;

public class FunctionalInterfacesExample {
  public static void main(String[] args) {
    Predicate isLong = str -> str.length() > 5;
    System.out.println(isLong.test("Example"));

    Function intToStr = i -> "Value: " + i;
    System.out.println(intToStr.apply(10));

    Consumer printer = s -> System.out.println("Hello, " + s);
    printer.accept("World");

    Supplier random = () -> Math.random();
    System.out.println(random.get());
  }
}

πŸ“˜ Detailed Explanation:

  • Predicate: Used in filter() operations to test conditions.
  • Function: Used in map() to transform values.
  • Consumer: Used in forEach() to process each element.
  • Supplier: Useful for lazy initialization or generating values on demand.
  • Operator variants: Useful for arithmetic and transformation pipelines.

πŸ› οΈ Use Cases:

  • Passing logic into methods like stream filters or processors.
  • Creating expressive APIs with functional hooks.
  • Replacing verbose anonymous inner classes in callbacks.