CAP477 · Unit 4: Collections and functional Java
Lambdas and streams
9 practice questions
Key points
- Lambda targets a functional interface; captured locals must be effectively final
- Intermediate ops are lazy; terminal op triggers execution
- A stream is single use
- Collectors: groupingBy, partitioningBy, joining, toMap
A lambda is a short anonymous function that implements a functional interface (one abstract method): (a, b) -> a + b, x -> x * x, () -> "s". A lambda may use local variables only if they are effectively final (never reassigned), else "local variables referenced from a lambda expression must be final or effectively final". Method references are shorthand: String::length, System.out::println, Integer::sum.
Core interfaces (java.util.function):
| Interface | Method | Example |
|---|---|---|
Function<T,R> | R apply(T) | x -> x * x; andThen, compose |
Predicate<T> | boolean test(T) | String::isEmpty; negate, or, and |
Consumer<T> | void accept(T) | System.out::println |
Supplier<T> | T get() | () -> "s" |
BiFunction<T,U,R>, UnaryOperator<T>, BinaryOperator<T> | R apply(T, U), T apply(T), T apply(T, T) | Integer::sum, Math::max |
For sq = x*x and inc = x+1: sq.andThen(inc).apply(4) is 17 and sq.compose(inc).apply(4) is 25.
Streams process data in a pipeline: source -> intermediate ops (lazy: filter, map, sorted, distinct, limit, skip, peek) -> terminal op (collect, forEach, count, sum, reduce, findFirst, anyMatch, max). Nothing runs until a terminal operation. A stream can be consumed once; reuse throws IllegalStateException. Short-circuiting stops early (findFirst after the first match: f1 f2 examined).
Examples (list 5, 2, 8, 1, 9, 2): filter(>2).map(*10) gives [50, 80, 90]; sum 27; distinct count 5; sorted().limit(3) gives [1, 2, 2]; average 4.5. Collectors: toList(), joining(",","[","]"), groupingBy(String::length) -> {1=[a], 2=[bb, cc], 3=[ddd]}, partitioningBy, counting, toMap. IntStream.rangeClosed(1,5).sum() is 15.
Optional wraps a possibly absent value: of, ofNullable, empty, isPresent, orElse, map; get() on empty throws NoSuchElementException.
Exam pitfall: peek or map without a terminal operation never executes. Also, count() on a stream whose size is known from the source may skip intermediate peek calls (verified on JDK 21), so do not rely on side effects.
Try two questions
A functional interface has:
- No methods
- Exactly one abstract method
- Only default methods
- At least two abstract methods
Show the answer
B. That single abstract method is what a lambda implements.
Stream.of("a","bb","cc","ddd").collect(Collectors.groupingBy(String::length)) gives:
- {a=1, bb=2, cc=2, ddd=3}
- {1=a, 2=bb, 3=ddd}
- [a, bb, cc, ddd]
- {1=[a], 2=[bb, cc], 3=[ddd]}
Show the answer
D. Computed: {1=[a], 2=[bb, cc], 3=[ddd]}.