Stream coding problems: interview questions & scenarios
These are the stream puzzle questions I use when I want to see whether you can turn a small requirement into the right pipeline shape. Answer it out loud first, then open the model answer, and revisit Stream coding problems when you want the worked examples behind the patterns.
Given a list of words, return the number of vowels in each word while preserving input order.
Tests mapping, primitive streams, encounter order
Show answerHide answer
Model answer
I would map each word to a count and collect into a LinkedHashMap if the caller needs key-value output in input order. The counting part is easiest with chars() and a predicate. In production, ask whether vowels are ASCII-only or language-aware.
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Main {
static long vowels(String word) {
return word.toLowerCase(Locale.ROOT).chars()
.filter(ch -> "aeiou".indexOf(ch) >= 0)
.count();
}
public static void main(String[] args) {
List<String> words = List.of("stream", "java", "sky");
Map<String, Long> counts = words.stream()
.collect(Collectors.toMap(
Function.identity(),
Main::vowels,
(left, right) -> left,
LinkedHashMap::new));
System.out.println(counts);
}
}
Output:
{stream=2, java=2, sky=0}
If duplicate words must appear twice, a map is the wrong result shape. Return List<WordCount> instead.
How I’d say it in the interview
"I treat this as one result per word. The stream maps each word to its vowel count, and LinkedHashMap keeps the same encounter order for display. I'd ask about duplicates before locking in a map."
Signals depth
Calling out that chars() walks UTF-16 code units. It is fine for this ASCII vowel exercise, but it is not a full Unicode text solution.
Red flags
Using a shared mutable counter outside the stream, or collecting into HashMap while claiming the output order is preserved.
Follow-ups interviewers ask next
What if duplicate words should keep separate counts?
Use a list of records:
record WordCount(String word, long count) { } List<WordCount> result = words.stream() .map(word -> new WordCount(word, vowels(word))) .toList();What if
ysometimes counts as a vowel?Make the vowel rule a parameter or predicate. Do not bury a language rule inside the pipeline and hope nobody notices.
Group a list of words into anagrams.
Tests groupingBy, classifier, deterministic output
Show answerHide answer
Model answer
The classifier is the sorted letters of each word after normalization. Then groupingBy collects all words with the same classifier into the same bucket. I usually use TreeMap in interview code so the printed output is deterministic.
import java.util.*;
import java.util.stream.Collectors;
public class Main {
static String key(String word) {
char[] chars = word.toLowerCase(Locale.ROOT).toCharArray();
Arrays.sort(chars);
return new String(chars);
}
public static void main(String[] args) {
List<String> words = List.of("Tea", "eat", "bat", "ate", "tab");
Map<String, List<String>> groups = words.stream()
.collect(Collectors.groupingBy(Main::key, TreeMap::new, Collectors.toList()));
System.out.println(groups.values());
}
}
Output:
[[bat, tab], [Tea, eat, ate]]
Sorting each word costs O(k log k), where k is the word length. For very long strings over a small alphabet, a character-count key can be cheaper.
How I’d say it in the interview
"The trick is to build a canonical key. Anagrams share the same letters, so after lowercasing and sorting the characters, Tea, eat and ate all land in the same group."
Signals depth
Separating the grouping classifier from the downstream collector, and mentioning deterministic output separately from correctness.
Red flags
Comparing every pair of words. That turns a grouping problem into O(n squared) work for no benefit.
Follow-ups interviewers ask next
What if the interviewer wants original casing preserved?
Normalize only for the key. Store the original word in the grouped values.
What if spaces and punctuation should be ignored?
Define that normalization before sorting. For example, strip non-letters with a clear regex or code point filter.
Sum the squares of the even numbers in a list.
Tests filter, mapToInt, sum, primitive streams
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
Find the most frequent element in a list, breaking ties by natural order.
Tests groupingBy, counting, max comparator, tie-breaker
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Convert List<Employee> into Map<department, List<name>>, with names sorted.
Tests groupingBy, mapping, collectingAndThen, sorted lists
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
Check whether all strings in a list are unique.
Tests distinct, count, set add, short-circuit trade-off
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
Return the nth highest distinct score using skip.
Tests distinct, sorting, skip, empty result
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
Zip two lists by index into labels like name:score.
Tests IntStream.range, index access, min length
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
Build a character histogram sorted by descending count, then character.
Tests codePoints, groupingBy, LinkedHashMap, sorted entries
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
Flatten a nested map of region to service to latency values.
Tests flatMap, map entries, flattening values, aggregation
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
Debug this pipeline: why does the sorted map print unsorted?
Tests sorted entries, toMap supplier, HashMap order
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