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:
- Predicate<T>: Tests a value and returns a boolean.
- Function<T, R>: Takes a value of type T and returns a value of type R.
- Consumer<T>: Takes a value of type T and returns nothing.
- Supplier<T>: Supplies a value of type T with no input.
- UnaryOperator<T>: A Function where input and output types are the same.
- 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.