1. University MCA (AI/ML) Semester 2
  2. CAP477
  3. Unit 4

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):

InterfaceMethodExample
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

Question 1 · Tier 1, Recall

A functional interface has:

  1. No methods
  2. Exactly one abstract method
  3. Only default methods
  4. At least two abstract methods
Show the answer

B. That single abstract method is what a lambda implements.

Question 2 · Tier 3, Apply

Stream.of("a","bb","cc","ddd").collect(Collectors.groupingBy(String::length)) gives:

  1. {a=1, bb=2, cc=2, ddd=3}
  2. {1=a, 2=bb, 3=ddd}
  3. [a, bb, cc, ddd]
  4. {1=[a], 2=[bb, cc], 3=[ddd]}
Show the answer

D. Computed: {1=[a], 2=[bb, cc], 3=[ddd]}.