The data for every example:
record Student(String name, int score, String city) {}
List<Student> students = List.of(
new Student("Priya", 200, "Bangalore"),
new Student("Rahul", 150, "Delhi"),
new Student("Aisha", 200, "Bangalore"),
new Student("Vikram", 110, "Mumbai"),
new Student("Meera", 175, "Delhi")
);Part 0's task#
List<String> top = students
.stream()
.filter(s -> s.score() >= 150) // keep passing students
.sorted(
Comparator.comparingInt(Student::score).reversed().thenComparing(Student::name)
)
.map(Student::name) // Student → String
.toList(); // Java 16+; unmodifiable
// [Aisha, Priya, Meera, Rahul]The operations you'll use#
| Operation | Does | Example |
|---|---|---|
filter(Predicate) | keep elements where the test is true | .filter(s -> s.score() >= 150) |
map(Function) | transform each element | .map(Student::name) |
mapToInt/Long/Double | transform to a primitive stream (Ch 7) | .mapToInt(Student::score) |
flatMap(Function<T, Stream<R>>) | transform each into a stream and flatten them into one | below |
sorted() / sorted(Comparator) | sort | |
distinct() | remove duplicates (uses equals/hashCode) | |
limit(n) / skip(n) | first n / all but the first n | |
peek(Consumer) | look at elements as they pass (for debugging) | |
terminal: toList(), collect(...) | gather results | Ch 6 |
count(), min(cmp), max(cmp) | ||
anyMatch, allMatch, noneMatch | true/false questions; stop early | .anyMatch(s -> s.score() == 200) |
findFirst(), findAny() | an Optional of one element (Ch 8) | |
reduce(identity, op) | combine everything into one value | below |
forEach(Consumer) | do something with each |
map vs flatMap — a favourite question#
map turns each element into one element. flatMap turns each element into a stream of elements, then joins all those streams into one:
List<List<String>> tags = List.of(List.of("bio", "exam"), List.of("chem"), List.of("bio", "lab"));
tags.stream().map(List::stream) // Stream<Stream<String>> — three little streams, still nested
tags.stream().flatMap(List::stream) // Stream<String> — "bio", "exam", "chem", "bio", "lab"
.distinct().sorted().toList();
// [bio, chem, exam, lab] map: [bio, exam] [chem] [bio, lab] → three separate lists
flatMap: [bio, exam] + [chem] + [bio, lab] → bio exam chem bio lab (one flat stream)reduce — folding everything into one value#
int total = students.stream().map(Student::score).reduce(0, Integer::sum); // 835
// start value ↑ ↑ how to combine two values0 + 200 = 200, 200 + 150 = 350, … = 835. (For sums, mapToInt(...).sum() is simpler and avoids boxing — Ch 7.)
Gotchas
Don't use
forEachto build up results (stream.forEach(s -> list.add(s))) — usecollect/toList. Side effects inside streams break with parallel streams (Ch 7) and hide intent.toList()(Java 16+) returns an unmodifiable list;collect(Collectors.toList())returns a modifiableArrayListin practice (not guaranteed). If you need to modify the result, usecollect(Collectors.toCollection(ArrayList::new)).Streams aren't always faster than loops. For simple work on small lists, a plain loop is equally fast or faster, and in DSA hot loops a
forover anint[]usually wins. Use streams for clarity, loops for tight performance-critical code.
Check yourself
4 questionsWrite a pipeline: the names of Delhi students, alphabetically.
Show answerHide answer
students.stream().filter(s -> s.city().equals("Delhi")).map(Student::name).sorted().toList() → [Meera, Rahul].
map vs flatMap?
Show answerHide answer
map produces one output per input; flatMap produces a stream per input and flattens them into one stream.
What does reduce(0, Integer::sum) do step by step?
Show answerHide answer
Starts from 0 and adds each score in turn to the running total, returning the final sum.
Why shouldn't you add to a list inside forEach?
Show answerHide answer
It's a side effect that breaks under parallel streams and is less clear; use collect/toList instead.