Functional Programming with Lambdas – Functional Interfaces, Streams, map, filter, reduce
This article is a conceptual guide to functional programming, including exam questions and reference tags.
In a Nutshell
Functional programming emphasizes computation through functions rather than state mutation. Lambda expressions are inline function literals that, in Java, bind to the runtime through Functional Interfaces—types with exactly one abstract method.
Core Explanation
A lambda expression captures anonymous behavior with parameters, a body, and an optional return type. The type is inferred from the target context—typically a Functional Interface like Predicate, Function, Consumer, or Supplier. Functional Interfaces enable higher-order functions: functions passed as values, returned from functions, or stored in variables. Central principles include pure functions (deterministic output from unchanged input, with no side effects), referential transparency, and immutability, which reduce coupling and simplify testing and parallelization.
Exam-Relevant Checklist
- Lambda syntax: parameter list, arrow, body, target type from Functional Interface
- Standard interfaces:
Function<T,R>,Predicate<T>,Consumer<T>,Supplier<T>,UnaryOperator<T>,BinaryOperator<T> - Streams, map, filter, flatMap, reduce, collect—explain briefly and justify typical complexity
- IHK relevance: imperative vs. functional approaches, avoiding side effects, benefits for testability and parallelization
- Practice: method references (ClassName::staticMethod, instance::method, Constructor::new)
- Security: no hidden side effects in lambdas, thread safety through immutability
- Economics: less boilerplate, clearer data flow, better maintainability, potentially fewer bugs
- Documentation: function contracts, input domain, side effects, concurrency concerns, complexity
Core Components
- Lambda expression syntax: parameters, body, return value
- Functional Interface with exactly one abstract method (SAM)
- Method references as a compact notation
- Higher-order functions: functions as parameters or return values
- Pure functions and side effects, testability, determinism
- Immutability and thread safety
- Stream pipeline, lazy evaluation, short-circuit operations
- Closures and effectively final in Java
- Optional and error patterns: Optional, Try, Either concepts
- Parallel streams, data independence, boxed vs. primitive streams
Practical Example
// Java: filter and transform data with lambdas and streams
List<String> names = List.of("Mila", "Tom", "Amir", "Mara")
List<Integer> lengths = names.stream()
.filter(n -> n.startsWith("M"))
.map(String::length)
.sorted()
.toList()
// Custom Functional Interface and lambda
@FunctionalInterface
interface IntOp { int apply(int a, int b) }
IntOp add = (a, b) -> a + b
IntOp max = Math::max
int r1 = add.apply(3, 4) // 7
int r2 = max.apply(5, 9) // 9
Explanation: The stream pipeline demonstrates map, filter, sorted, and toList. The lambdas are pure and free of side effects.
Advantages and Disadvantages
Advantages
- Less boilerplate; clear, declarative style
- Better testability through pure functions
- Simple parallelization thanks to immutability
- High reusability through combinators
Disadvantages
- Learning curve with abstractions like higher-order functions
- Harder debugging in pipelines
- Careless captures can hold memory
- Java limitations: effectively final and type erasure
Common Exam Questions (with Short Answers)
-
What is a lambda expression in Java and how is its type determined? An anonymous function literal; its type is inferred from the target context, typically a Functional Interface with a single abstract method.
-
Name four core Functional Interfaces from java.util.function.
Function<T,R>,Predicate<T>,Consumer<T>,Supplier<T>, plus operator variants that map T to T. -
How does a method as a lambda differ from a method reference? Method references point directly to existing methods and are equivalent to a lambda but shorter and more readable.
-
What does effectively final mean in closures? Local variables used in lambdas must not be reassigned after initialization; the JVM can safely capture them.
-
What is referential transparency and why does it matter? An expression can be replaced by its value without changing program behavior. This promotes testability and reasoning about code.
-
How does reduce work in a stream pipeline? It combines elements iteratively using an associative accumulator and optional identity value—for example, reduce(0, Integer::sum).
-
What are the risks with parallel streams? Non-associative accumulators produce incorrect results; lambdas with side effects are unsafe.
-
How do you model errors functionally? Use values like Optional for absence, Try or Either for success or failure, instead of throwing exceptions.
-
What is the difference between an imperative loop and a functional pipeline? Imperative: explicit mutation and control flow. Functional: declarative data flow, immutability, easier to test.
-
How do Functional Interfaces compare to true function types? Java uses SAM types as a workaround; languages like Kotlin, Scala, and Haskell have native function types with proper arity.
Key References
- https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
- https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html
- https://en.wikipedia.org/wiki/Functional_programming
Recommended Reading
Keine Bücher für Kategorie "programming-languages" gefunden.



