The Streams API
The Streams API processes collections declaratively with map, filter, collect and friends. Stream coding questions (group by, top N, frequency counts) are standard in Java backend interviews, along with lazy evaluation and parallel streams.
What you will learn
- Know intermediate vs terminal operations and laziness
- Use map, flatMap, filter, reduce, collect
- Group and aggregate with Collectors
- Know when parallel streams help or hurt
Key concepts
Pipeline
Source → zero or more intermediate operations (filter, map, sorted, distinct; lazy, return a stream) → one terminal operation (collect, forEach, count, findFirst; runs the pipeline). A stream can be used once.
Laziness
Nothing runs until the terminal operation, and elements flow one at a time through the whole pipeline, so findFirst can stop early.
flatMap
Maps each element to a stream and flattens them: orders.stream().flatMap(o -> o.items().stream()).
Parallel streams
Split work across the common ForkJoinPool. Help for large CPU-bound work on arrays; hurt for small lists, I/O inside the pipeline, or shared mutable state.
Step by step
Interview favourites
// frequency of each character
Map<Character, Long> freq = "programming".chars().mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
// first non-repeated character
Character first = freq.entrySet().stream().filter(e -> e.getValue() == 1).map(Map.Entry::getKey).findFirst().orElse(null);
// second highest salary
Optional<Integer> second = employees.stream().map(Employee::salary).distinct()
.sorted(Comparator.reverseOrder()).skip(1).findFirst();
// average salary per department
Map<String, Double> avg = employees.stream()
.collect(Collectors.groupingBy(Employee::dept, Collectors.averagingInt(Employee::salary)));
// highest-paid per department
Map<String, Optional<Employee>> top = employees.stream()
.collect(Collectors.groupingBy(Employee::dept, Collectors.maxBy(Comparator.comparingInt(Employee::salary))));
// partition into even and odd
Map<Boolean, List<Integer>> parts = nums.stream().collect(Collectors.partitioningBy(n -> n % 2 == 0));Examples
Laziness in action
Stream.of("a", "bb", "ccc", "dddd")
.filter(s -> { System.out.println("filter " + s); return s.length() > 1; })
.map(s -> { System.out.println("map " + s); return s.toUpperCase(); })
.findFirst();
// filter a, filter bb, map bb → stops; ccc and dddd are never touchedPractise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Group words by length and sort each group alphabetically.
- Flatten a List<List<Integer>> and find the sum of squares of odd numbers.
- Convert a list of employees to Map<id, name> and handle duplicate ids.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
map vs flatMap?
map turns each element into exactly one result. flatMap turns each element into a stream of results and flattens all of them into one stream, for one-to-many cases.
What does Collectors.toMap do on duplicate keys?
It throws IllegalStateException. Pass a merge function as the third argument, such as (a, b) -> a, to choose which value wins.
Stream.toList() vs collect(Collectors.toList())?
Stream.toList (Java 16) returns an unmodifiable list. Collectors.toList makes no guarantee and in practice returns a mutable ArrayList.
Summary
Streams are lazy pipelines of intermediate operations ending in one terminal operation. Master groupingBy, partitioningBy, toMap with merge, flatMap and reduce, and use parallel streams only for large CPU-bound work.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus