Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Modern Java

    Stream Operations

    record Student(String name, int score, String city) {}

    Chapter 5 of 115 min readOften asked in interviews

    The data for every example:

    Java
    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#

    Java
    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#

    OperationDoesExample
    filter(Predicate)keep elements where the test is true.filter(s -> s.score() >= 150)
    map(Function)transform each element.map(Student::name)
    mapToInt/Long/Doubletransform to a primitive stream (Ch 7).mapToInt(Student::score)
    flatMap(Function<T, Stream<R>>)transform each into a stream and flatten them into onebelow
    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 resultsCh 6
    count(), min(cmp), max(cmp)
    anyMatch, allMatch, noneMatchtrue/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 valuebelow
    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:

    Java
    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]
    Output
      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#

    Java
    int total = students.stream().map(Student::score).reduce(0, Integer::sum); // 835
    //                                              start value ↑   ↑ how to combine two values

    0 + 200 = 200, 200 + 150 = 350, … = 835. (For sums, mapToInt(...).sum() is simpler and avoids boxing — Ch 7.)

    Gotchas

    • Don't use forEach to build up results (stream.forEach(s -> list.add(s))) — use collect/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 modifiable ArrayList in practice (not guaranteed). If you need to modify the result, use collect(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 for over an int[] usually wins. Use streams for clarity, loops for tight performance-critical code.

    Check yourself

    4 questions
    1

    Write a pipeline: the names of Delhi students, alphabetically.

    Show answer

    students.stream().filter(s -> s.city().equals("Delhi")).map(Student::name).sorted().toList() → [Meera, Rahul].

    2

    map vs flatMap?

    Show answer

    map produces one output per input; flatMap produces a stream per input and flattens them into one stream.

    3

    What does reduce(0, Integer::sum) do step by step?

    Show answer

    Starts from 0 and adds each score in turn to the running total, returning the final sum.

    4

    Why shouldn't you add to a list inside forEach?

    Show answer

    It's a side effect that breaks under parallel streams and is less clear; use collect/toList instead.