Java - Lambdas & Streams

Lambdas & Streams

Functional Interfaces

@FunctionalInterface interface Combiner { int apply(int a, int b); }
Combiner c = (a,b) -> a + b;
int r = c.apply(2,3);

Method References

java.util.function.Function f = Integer::parseInt;

Stream Basics

import java.util.*;
import java.util.stream.*;
List xs = List.of(1,2,3,4,5);
int sumOfSquares = xs.stream()
  .map(x -> x * x)
  .reduce(0, Integer::sum);

Collecting

Map counts = xs.stream()
  .collect(Collectors.groupingBy(x -> x % 3, Collectors.counting()));

Optional

Optional maybe = xs.stream().filter(x -> x > 10).findFirst();
int val = maybe.orElse(0);

Parallel Streams (Use with Care)

  • Only when work per element is heavy and data is large.
  • Beware of thread-unsafe collectors or side effects.
Avoid stateful lambdas. Keep operations pure for correctness and easier reasoning.

Try it

  1. Map a list of names to uppercase and collect to a Set.
  2. Compute the sum of squares of even numbers with streams.
  3. Transform a list into a map of value → frequency using Collectors.groupingBy.