Functional Programming in Java: Streams, Lambdas, and Functional Interfaces
This article explains Java's functional programming support introduced in Java 8, covering the concepts of stateless functions, functional interfaces, lambda expressions, and the Stream API, with clear code examples and guidance on when to apply FP in Java projects.
What is Functional Programming?
Functional programming (FP) treats computation as evaluation of mathematical functions, emphasizing stateless, pure functions. Java added FP support in Java 8 via lambda expressions, the Stream API, and functional interfaces.
Why Use FP in Java?
Traditional OOP code often requires boilerplate, such as anonymous inner classes for Runnable. FP allows concise expressions, e.g., a one‑line lambda replaces several lines of anonymous class.
Key Concepts
Stateless functions: output depends only on inputs.
Functional interfaces: interfaces with a single abstract method, marked @FunctionalInterface.
Lambda expressions: compact syntax for implementing functional interfaces.
Stream API: enables chainable intermediate operations (map, filter) and terminal operations (max, collect).
Code Examples
Anonymous class example:
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("do something...");
}
};Lambda equivalent:
Runnable runnable = () -> System.out.println("do something...");Using Stream, lambda, and functional interfaces:
public class Demo {
public static void main(String[] args) {
Optional<Integer> result = Stream.of("a", "be", "hello")
.map(s -> s.length())
.filter(l -> l <= 3)
.max((o1, o2) -> o1 - o2);
System.out.println(result.get()); // prints 2
}
}Functional interface definition example (Comparator):
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
// default and static methods may also be present
}Lambda instantiation of Comparator:
Comparator<Person> comparator = (p1, p2) -> Integer.compare(p1.getAge(), p2.getAge());When to Use FP
FP shines in data‑processing, scientific computing, and parallel workloads, but for large business logic heavy on state, OOP may remain more appropriate.
Summary
Java’s functional programming features—lambda expressions, streams, and functional interfaces—enable more concise, expressive code, especially useful in big‑data and parallel processing scenarios.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Alibaba Cloud Developer
Alibaba's official tech channel, featuring all of its technology innovations.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
