Answering Stream questions in Java 8 means knowing three moves cold: build a stream from a collection, chain intermediate operations such as filter, map and sorted, and finish with a terminal operation such as collect, forEach or reduce. Streams do not store data and do not change the source; they describe a pipeline that runs only when the terminal operation is reached. Set up a project with the JDK 8 or newer and you can answer any typical question about mapping, filtering, grouping, counting and reducing in a few lines.

What You'll Need

  • A JDK 8 or newer installed, with javac and java on your path (check with java -version).
  • A small Java project or a single class file you can compile and run; an IDE such as IntelliJ IDEA, Eclipse or VS Code with the Java extension is convenient but not required.
  • Basic knowledge of List and lambda syntax: x -> x * 2 is a function, (x, y) -> x + y has two parameters.
  • A sample data class to work with, for example a Person with a name, age and city.
  • The static import import static java.util.stream.Collectors.*; if you want to call toList(), groupingBy() and joining() without the class prefix.

Step-by-Step

  1. Create the sample data. Make a list of objects: List<Person> people = Arrays.asList(new Person("Ada", 31, "Leeds"), new Person("Ben", 24, "Oslo"), new Person("Cara", 45, "Leeds"));. Give the class getters such as getAge() and getCity(), either written by hand or generated by your IDE. Every example below builds on this list.
  2. Open a stream. Call people.stream(). Use Arrays.stream(array) for arrays, Stream.of(a, b, c) for loose values, and IntStream.range(1, 10) when the question is about numbers. There is also parallelStream(), but answer questions with a sequential stream first; parallelism is rarely the point being tested.
  3. Filter. To answer "which people are over 30", write people.stream().filter(p -> p.getAge() > 30). Combine conditions with && and || inside one lambda, or chain a second filter. The predicate must return a boolean, so p -> p.getAge() > 30 is correct and p -> p.getAge() is not.
  4. Map. To turn objects into names, add .map(Person::getName), giving a Stream<String>. Use mapToInt(Person::getAge) when you need primitive numbers, because that unlocks sum(), average(), max() and min(). Use flatMap when each element produces a list and you want one flat stream.
  5. Sort and limit. Insert .sorted(Comparator.comparing(Person::getAge)) for oldest or youngest order, add .reversed() for the opposite, and .limit(5) to keep the first five. distinct() removes duplicates by equals and hashCode, so override both in your class if duplicates keep appearing.
  6. Finish with a terminal operation. Use .collect(Collectors.toList()) to get a list, .forEach(System.out::println) to print, .count() for a size, and .anyMatch(p -> p.getAge() > 40) for a yes/no answer. On an IntStream, .sum() and .average() answer the numeric questions directly.
  7. Group and aggregate. For "count people per city", write people.stream().collect(groupingBy(Person::getCity, counting())), which yields a Map<String, Long>. Swap counting() for averagingInt(Person::getAge) to average ages per city, or use joining(", ") after mapping to names for a comma-separated string.
  8. Reduce. To answer "sum of ages" manually, use people.stream().map(Person::getAge).reduce(0, Integer::sum). The identity (0) is the starting value and the second argument combines two values into one, which works the same for products with an identity of 1.
  9. Handle optional results. Terminal operations such as findFirst(), max() and average() return Optional, because the stream might be empty. Call .orElse(0) or .orElseThrow() to unwrap safely; never call get() without knowing the value is present.
  10. Compile and check the answer. Run the program and verify output against a manual count. If the compiler rejects a lambda, check that the predicate returns boolean and the mapper returns a value of the expected type. If the result type looks wrong, inspect each step with .peek(System.out::println) temporarily.

Common Mistakes

The biggest mistake is reusing a stream. A stream can be consumed once, so calling a terminal operation twice throws IllegalStateException: stream has already been operated upon or closed. Build a new stream from the list, or store the collected result in a variable.

Second, expecting filter or map to change the original list. Streams never mutate the source, and the returned collection is a new one. Third, forgetting that groupingBy returns Long counts, not Integer, which causes confusing generic errors. Fourth, using == instead of .equals inside predicates for strings, which compares references rather than text.

Another frequent slip is putting side effects into map to add to an external list. That breaks with parallel streams; use collect instead. Finally, do not overuse forEach to build results, because it hides intent and gives no return value.

Tips

Prefer method references such as Person::getName over lambdas when the lambda merely calls one method, since it reads more clearly. Use mapToInt early when the pipeline is numeric, and boxed() to return to object streams only when necessary.

Build pipelines one operation at a time and compile often, placing each call on its own line so compiler error columns point to the failing step. Collectors like summarizingInt give count, sum, min, max and average in one pass, which is handy for interview-style questions. Keep streams short: if a pipeline grows past six or seven steps, extract it into a named method with a comment stating the business rule.

Troubleshooting

If you see stream has already been operated upon or closed, you reused a variable holding a stream. Rebuild it from the source list.

If the pipeline returns nothing, check the filter predicate first; a condition like p.getAge() > 90 may simply match no element, and Optional.empty or an empty list is the correct answer.

If you get a NullPointerException inside a lambda, a getter returned null, often because the stream contains a null element. Filter it out with Objects::nonNull before other operations.

If findFirst or max gives Optional and you are stuck, unwrap with orElse and supply a sensible default such as 0 or an empty string. If a class does not sort as expected, check that Comparator.comparing points to the right getter and that numeric types match.

Frequently Asked Questions

What is the difference between map and flatMap?

map transforms each element one-to-one; flatMap transforms each element into a stream and merges them into one stream, which suits lists of lists.

Can I reuse a stream?

No. A stream is consumable once. Reopen it from the source collection each time.

Do streams change my original list?

No. Streams read from the source and return new values; the original collection is untouched.

What does collect do?

It gathers the stream into a result such as a list, set, map or string, using a collector from Collectors.

How do I loop over a stream?

Use forEach for simple printing, but prefer collect when you need a result, since side effects are discouraged.

Why does count return long?

Streams can be larger than an integer, so count() returns long; convert with a cast only when you know the size fits.