Course contents

Stream basics: interview questions & scenarios

Premium12 questions · 21 what-if follow-ups

These are the stream-basics questions I use to check whether you can see the source, pipeline stages and terminal operation behind fluent Java code. Answer it out loud first, then open the model answer, and revisit the lessons when a detail feels fuzzy: Introduction to Java streams, How a stream pipeline executes, Intermediate vs terminal operations, findFirst vs findAny and short-circuiting and Primitive streams: IntStream, LongStream and DoubleStream.

Question 1. ConceptWarm-upAsked very often

What is a Java stream, and how is it different from a collection?

Tests stream shape, source versus pipeline, terminal operation

Show answerHide answer2 follow-ups

Model answer

A Java stream is a one-shot pipeline over a source. The source can be a List, array, file, generated sequence or custom Spliterator; the stream describes operations to apply as elements are pulled through. A collection stores elements. A stream does not store elements as its main job, and it is not meant to be reused after a terminal operation.

The shape is:

source -> intermediate operations -> terminal operation

filter, map, peek, sorted and limit are intermediate operations because they return another stream. count, sum, toList, findFirst, forEach and collect are terminal operations because they start traversal and produce a result or final side effect.

How I’d say it in the interview

"A stream is a recipe over a source, not the pantry. The list owns the data; the stream records the pipeline. Nothing really moves until a terminal operation pulls, and after that pull the stream is consumed."

Signals depth

Saying that some operations, like sorted and distinct, may buffer during execution, but that does not turn the stream into a reusable collection.

Red flags

"A stream is a faster list" or "a stream stores filtered results after each step".

Follow-ups interviewers ask next

  1. What if I need to traverse the same data twice?

    Store the source, such as the List, Path or query description, and create a fresh stream for each traversal. If the result is small and expensive to recompute, materialize it deliberately into a collection and say that cost out loud.

  2. What if the source is a file?

    A stream from Files.lines(path) is resource-backed, so use try-with-resources. Collection streams usually do not need manual closing.

Question 2. What does it print?CoreAsked very often

What does this print, and why does peek wait until count()?

Tests laziness, vertical traversal, terminal operation

Show answerHide answer2 follow-ups

Model answer

import java.util.List;

public class Main {
    public static void main(String[] args) {
        var pipeline = List.of("ann", "bob", "carla").stream()
                .peek(name -> System.out.println("peek " + name))
                .filter(name -> name.length() > 3)
                .map(name -> {
                    System.out.println("map " + name);
                    return name.toUpperCase();
                });

        System.out.println("built");
        System.out.println(pipeline.toList());
    }
}

It prints:

built
peek ann
peek bob
peek carla
map carla
[CARLA]

The intermediate operations are lazy. Creating pipeline builds stage objects; it does not traverse the list. toList() is the terminal operation, so it starts pulling elements through the chain. For a stateless sequential pipeline, elements move vertically: ann is peeked and filtered out, bob is peeked and filtered out, then carla is peeked, mapped and added to the result.

How I’d say it in the interview

"The only line before traversal is built. Then the terminal operation pulls one name at a time. The first two names never reach map, and carla goes from peek to filter to map before the final list is printed."

Signals depth

Mentioning vertical execution and operation fusion, not imagining a temporary list after every intermediate operation.

Red flags

Printing all peek lines when the pipeline is created, or printing map carla before the peeks for ann and bob.

Follow-ups interviewers ask next

  1. What if the terminal operation were removed?

    Only built would print. A pipeline with no terminal operation is a description, not a traversal.

  2. What if this were a parallel stream?

    Laziness still applies, but print order becomes a poor teaching tool because multiple elements can be processed by different worker threads.

Question 3. What does it print?SeniorCommonly asked

What does this print on Java 21, and why can count() skip peek?

Tests SIZED flag, count optimization, peek side effects

Model answer, how to say it, 2 follow-ups: unlock with the Java Pass

Question 4. DebuggingCoreAsked very often

Why does this code throw IllegalStateException: stream has already been operated upon or closed, and how would you fix it?

Tests one-shot streams, linked pipeline, supplier pattern

Model answer, how to say it, 2 follow-ups: unlock with the Java Pass

Question 5. ConceptWarm-upAsked very often

Which operations here are intermediate and which are terminal, and what runs when?

Tests operation categories, laziness, return types

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 6. ScenarioCoreCommonly asked

When would you use a stream, and when would you keep a loop?

Tests readability, side effects, control flow trade-off

Model answer, how to say it, 2 follow-ups: unlock with the Java Pass

Question 7. ConceptCoreAsked very often

What is the difference between findFirst() and findAny()?

Tests encounter order, short-circuiting, parallel choice

Model answer, how to say it, 2 follow-ups: unlock with the Java Pass

Question 8. What does it print?CoreCommonly asked

What does this print, and why does the infinite stream terminate?

Tests short-circuiting, infinite streams, findFirst

Model answer, how to say it, 2 follow-ups: unlock with the Java Pass

Question 9. ScenarioCoreAsked very often

Why would you write mapToInt(Order::cents).sum() instead of map(Order::cents).reduce(0, Integer::sum)?

Tests primitive streams, boxing, numeric terminals

Model answer, how to say it, 2 follow-ups: unlock with the Java Pass

Question 10. CodingWarm-upCommonly asked

Write a method that returns the first paid order id, or Optional.empty() if none exists.

Tests filter, map, findFirst, Optional

Model answer, how to say it, 2 follow-ups: unlock with the Java Pass

Question 11. DebuggingCoreCommonly asked

This pipeline uses sorted().findFirst() to get the cheapest product. What would you change?

Tests stateful operations, min, unnecessary sorting

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 12. CodingSeniorSometimes asked

Write a method that counts non-blank lines in a file. What stream detail must the method handle?

Tests resource-backed streams, try-with-resources, predicates

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Premium question set

Keep reading with the Java Pass

The rest of this question set is part of Java One-Stop Interview Prep: in-depth explanations, diagrams, model answers and how to say them in the interview.

From ₹199 · one-time payment · No auto-renewal

Lessons in Stream basics