Lambda Expressions
Lambda Expressions
Java 8 introduced lambda expressions — concise anonymous functions that implement a functional interface (an interface with exactly one abstract method).
Functional Interfaces
A functional interface has a single abstract method. The @FunctionalInterface annotation is optional but recommended:
@FunctionalInterface
interface Greeting {
String greet(String name);
}
Java provides built-in functional interfaces in java.util.function:
Function<T, R>— takes T, returns RPredicate<T>— takes T, returns booleanConsumer<T>— takes T, returns voidSupplier<T>— takes nothing, returns T
Lambda Syntax
A lambda replaces the boilerplate of an anonymous class:
// Full syntax
Greeting g1 = (String name) -> { return "Hello, " + name; };
// Simplified — type inference, no braces for single expression
Greeting g2 = name -> "Hello, " + name;
System.out.println(g2.greet("Alice")); // Hello, Alice
Method References
When a lambda simply delegates to an existing method, use a method reference:
// Static method reference
Function<String, Integer> parse = Integer::parseInt;
// Instance method reference
Function<String, String> upper = String::toUpperCase;
System.out.println(parse.apply("42")); // 42
System.out.println(upper.apply("hello")); // HELLO
Streams: map, filter, reduce
The Streams API lets you process collections in a functional pipeline:
import java.util.*;
import java.util.stream.*;
List<Integer> nums = List.of(1, 2, 3, 4, 5);
// filter: keep only elements matching a predicate
List<Integer> evens = nums.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
// [2, 4]
// map: transform each element
List<String> strs = nums.stream()
.map(n -> "num:" + n)
.collect(Collectors.toList());
// reduce: combine all elements into one value
int sum = nums.stream()
.reduce(0, (a, b) -> a + b);
// 15
Your Task
-
Use
stream().filter()to keep only strings with length > 3 from a list, then print each on its own line in order. -
Use
stream().map()to convert a list of integers to their squares, then print each on its own line. -
Use
stream().reduce()to compute the product of a list of integers and print the result. -
Combine
filter,map, andreduce: given a list of integers, keep only the even numbers, square them, and sum the results. Print the final sum.