Java Essentials: Streams and Lambda Expressions
The Lambda Syntax
A lambda is a compact way to write a function as an expression. Instead of an anonymous class with boilerplate, you write parameters, an arrow, and a body. Lambdas are everywhere in modern Java, and they pair perfectly with the Streams API.
List<String> names = List.of("ada", "grace", "alan");
names.forEach(name -> System.out.println(name.toUpperCase()));Here the lambda takes one name and prints its uppercase form. The arrow -> separates parameters from the body.
Streams Process Data in Steps
A stream is a sequence of elements that flows through a pipeline of operations. You start from a source, apply zero or more intermediate operations such as filter and map, and finish with a terminal operation such as collect or count. Intermediate operations are lazy, while the terminal operation triggers the work.
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);
int total = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(n -> n * n)
.sum();
System.out.println(total);This pipeline keeps the even numbers, squares each of them, and adds them up: 4 plus 16 plus 36 equals 56. Streams encourage thinking in terms of data transformation instead of index bookkeeping.
Common Stream Operations
- filter - keeps elements that match a predicate.
- map - transforms each element into another value.
- sorted - orders the elements.
- distinct - removes duplicates.
- collect - gathers results back into a list, set, or map.
List<String> result = names.stream()
.filter(n -> n.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());The method reference String::toUpperCase is a shorthand for the lambda n -> n.toUpperCase(). Both are valid; pick whichever reads clearly.
Key Points
- Lambdas express functions concisely with arrow syntax.
- Streams process collections through a lazy pipeline.
- filter, map, and collect cover most everyday transformations.
- Method references shorten simple lambdas even further.