
Java Functional Essentials – Chapter 2: Creating and Using Streams
This lesson introduces functional interfaces, which are the foundation of Java's functional programming features like lambdas and streams. You'll learn what they are, how they work, and how to use built-in types like Predicate, Function, Consumer, and Supplier.
What Is a Functional Interface?
A functional interface is an interface that contains exactly one abstract method. It may also contain default and static methods.
These are used primarily with lambda expressions and method references.
You can mark them with the @FunctionalInterface annotation:
@FunctionalInterface
interface Greeting {
void sayHello(String name);
}Usage with lambda:
Greeting g = (name) -> System.out.println("Hello, " + name);
g.sayHello("Alice");Built-in Functional Interfaces (java.util.function)
Interface Signature Use Case Example
Predicate<T> boolean test(T t) Filtering (returns true/false)
Function<T, R> R apply(T t) Transforming input to output
Consumer<T> void accept(T t) Consuming without return
Supplier<T> T get() Supplying a value without input
Examples
Predicate Example
Predicate<String> isLong = s -> s.length() > 5;
System.out.println(isLong.test("Banana")); // trueFunction Example
Function<String, Integer> getLength = s -> s.length();
System.out.println(getLength.apply("Java")); // 4Consumer Example
Consumer<String> printer = s -> System.out.println("Hello " + s);
printer.accept("Bob"); // Hello Bob
Supplier Example
Supplier<Double> random = () -> Math.random();
System.out.println(random.get());Summary
A functional interface has exactly one abstract method.
Java provides many built-in ones under
java.util.function.These are essential for stream operations, lambdas, and concise functional code.
Assignment: Lesson 2 – Functional Interfaces
Objective:
Practice using built-in functional interfaces with real use cases.
Conceptual Questions
Use these to reinforce understanding before or after coding:
What is a functional interface? Why is it important in Java 8 and above?
What are the rules for defining a functional interface?
Name and describe the purpose of each of the following built-in functional interfaces:
Predicate<T>Function<T, R>Consumer<T>Supplier<T>
What is the difference between a
Consumer<T>and aFunction<T, R>?Can a functional interface have default or static methods? Why or why not?
Assignment 1
Task:
Write a program that:
Uses a
Predicate<String>to filter strings starting with"J"Uses a
Function<String, Integer>to convert names to their lengthsPrint the name and its length only if it starts with
"J"
James (5)
Julia (5)Assignment 2 – Challenge
Task:
Use
Supplier<List<String>>to generate a list of fruit names.Use a
Consumer<String>to print each fruit with"Delicious: "prefix.Use a
Predicate<String>to skip any fruit with less than 5 characters.Combine it all in a pipeline.
Sample Output:
Delicious: Banana
Delicious: Orange
Delicious: Papaya