Sub topic 1
Refresher: Lambdas and Method References
Lambdas and Method References
A lambda is a short function you can pass to a method. It has parameters, an arrow, and a body: name -> name.length() > 3. A method reference is a shorter way to write a lambda that only calls one existing method. For example, String::toUpperCase means the same as s -> s.toUpperCase(). Streams use lambdas and method references to describe what to do with each element.
What Is a Stream?
A stream is a sequence of elements that you process one step at a time. A collection, such as a List, stores data. A stream does not store data. It reads data from a source and passes each element through your steps. Once a stream has been used, you cannot use it again.
Anatomy of a Stream Pipeline
A pipeline is a chain of stream steps. It has three parts:
- A source, which provides the elements.
- Intermediate operations, which turn a stream into a new stream.
filterandmapare examples. - A terminal operation, which produces a result and ends the stream.
collectis an example.
Creating Streams
You can create a stream in several ways:
| Source | Code |
|---|---|
| A collection | `list.stream()` |
| An array | `Arrays.stream(array)` |
| Separate values | `Stream.of("a", "b", "c")` |
filter and map
filter keeps only the elements that pass a test. map changes each element into a new value.
import java.util.List;
import java.util.stream.Collectors;
public class FilterMapExample {
public static void main(String[] args) {
List<String> names = List.of("alice", "bob", "carol", "dave");
List<String> result = names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(result); // [ALICE, CAROL, DAVE]
}
}The lambda in filter drops "bob" because its length is not greater than 3. Then map turns each name that is left into upper case.
Exercise
Using Stream.of(1, 2, 3, 4), write a pipeline that keeps the even numbers and multiplies each one by 10.
Show answer
Stream.of(1, 2, 3, 4).filter(n -> n % 2 == 0).map(n -> n * 10).collect(Collectors.toList()) gives [20, 40].
Exercise
Rewrite the lambda s -> s.toLowerCase() as a method reference.
Show answer
String::toLowerCase