In Phase 7 you learned the stream basics. This last phase is where most of the interview time actually goes: questions that combine two or three ideas into one pipeline.
Don’t try to memorise 18 answers. Almost every one is built from the same small set of pieces, so learn the pieces first, then watch them combine.
We use the same employees as before:
record Employee(String name, String department, int age, double salary) {}
List<Employee> employees = List.of(
new Employee("Asha", "Engineering", 29, 1_800_000),
new Employee("Ravi", "Engineering", 35, 1_200_000),
new Employee("Meena", "HR", 41, 900_000),
new Employee("John", "Sales", 26, 700_000),
new Employee("Priya", "Engineering", 26, 1_200_000),
new Employee("Kiran", "Sales", 38, 1_500_000),
new Employee("Fatima", "HR", 30, 650_000),
new Employee("Arjun", "Finance", 45, 2_100_000)
);
The examples need these imports:
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
The pattern to recognise
Nearly every stream answer has this shape:
list.stream()
.filter(...) // keep some
.map(...) // change each
.sorted(...) // order them
.collect(...) // build the result
And the result-building end is almost always one of these collectors:
| Collector | Gives you | Example result |
|---|---|---|
Collectors.toList() |
a List |
[Asha, Ravi] |
Collectors.toSet() |
a Set, duplicates gone |
[HR, Sales] |
Collectors.joining(", ") |
one String |
"Asha, Ravi" |
Collectors.groupingBy(key) |
Map<K, List<T>> |
{HR=[Meena, Fatima]} |
Collectors.groupingBy(key, downstream) |
Map<K, whatever downstream makes> |
{HR=2} |
Collectors.partitioningBy(test) |
Map<Boolean, List<T>> |
{false=[...], true=[...]} |
Collectors.toMap(key, value) |
Map<K, V> |
{Asha=1800000.0} |
Collectors.counting() |
a Long (used as a downstream) |
3 |
The downstream collectors in the picture above (counting, averagingDouble, maxBy, mapping, joining) are what turn groupingBy from “make buckets” into “answer a question about each bucket”.
Warm-up: redo the earlier problems with streams
Before the new puzzles, rewrite some loop problems from earlier phases. You know the answers already, so you can focus on the stream form:
// 1. max and min of an array
int max = Arrays.stream(arr).max().getAsInt();
int min = Arrays.stream(arr).min().getAsInt();
// 3. second largest, ignoring duplicates: [10, 5, 20, 8, 20] → 10
int second = Arrays.stream(arr).boxed()
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst()
.orElseThrow();
// 5. move zeros to the end: [0, 1, 0, 3, 12] → [1, 3, 12, 0, 0]
int[] moved = IntStream.concat(
Arrays.stream(arr).filter(x -> x != 0),
Arrays.stream(arr).filter(x -> x == 0)
).toArray();
// 11. character frequency, in order of first appearance
Map<Character, Long> freq = "programming".chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
// {p=1, r=2, o=1, g=2, a=1, m=2, i=1, n=1}
// 12. remove duplicates, keep order
List<Integer> unique = list.stream().distinct().toList();
// 13. common elements
List<Integer> common = a.stream().filter(new HashSet<>(b)::contains).toList();
// 14. union
List<Integer> union = Stream.concat(a.stream(), b.stream()).distinct().toList();
// 16. word frequency
Map<String, Long> words = Arrays.stream(text.split("\\s+"))
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
// {java=3, spring=2, kafka=1}
// 17. most frequent element
int mostFrequent = Stream.of(1, 3, 2, 3, 4, 3, 2)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElseThrow(); // 3
Three new things showed up there:
"text".chars()gives anIntStreamof character codes, notchars..mapToObj(c -> (char) c)turns each code back into aCharacter.Function.identity()means “the element itself”, sogroupingBy(Function.identity(), ...)groups equal elements together..boxed()turns anIntStreaminto aStream<Integer>, which you need before using aComparatorlikereverseOrder().
groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()) is the stream version of every counting loop you’ve written. If you remember one line from this article, make it that one.
Now the puzzles.
Counting and frequency puzzles
33. Find the duplicate elements in a list
Input: [1, 2, 3, 2, 4, 1, 5, 1] → Output: [1, 2]
Plan: count each number, then keep the ones with a count above 1.
List<Integer> nums = List.of(1, 2, 3, 2, 4, 1, 5, 1);
List<Integer> duplicates = nums.stream()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.toList();
// [1, 2]
Notice the shape: collect into a map, then stream the map’s entrySet() again. You’ll see it in many puzzles below.
The shorter trick you’ll see online:
Set<Integer> seen = new HashSet<>();
Set<Integer> duplicates = nums.stream()
.filter(n -> !seen.add(n)) // add returns false the second time
.collect(Collectors.toCollection(LinkedHashSet::new));
// [2, 1] in the order the repeats were found
It works, but the lambda changes a set outside the stream (a “side effect”), which breaks if the stream ever runs in parallel. Show the first version, and mention the second as a trick you know but wouldn’t ship.
34. First non-repeating character with streams
Input: "swiss" → Output: w
Count with a LinkedHashMap so the order of first appearance is kept, then find the first entry with count 1:
Character first = "swiss".chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
// w
The trap: use HashMap (the default when you leave out LinkedHashMap::new) and you might get i instead of w, because a HashMap has no order. Change == 1 to > 1 and you get the first repeating character in the “appears more than once” sense from problem 10.
35. Word frequency, most common first
Input: "java spring java kafka spring java docker kafka"
Output: {java=3, kafka=2, spring=2, docker=1}, ties in alphabetical order
This combines problem 16 (count) with problem 22 (sort a map by value):
Map<String, Long> result = Arrays.stream(text.split("\\s+"))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed()
.thenComparing(Map.Entry.comparingByKey()))
.collect(Collectors.toMap(
Map.Entry::getKey, Map.Entry::getValue, (x, y) -> x, LinkedHashMap::new));
Three steps: count, sort the entries, collect into a LinkedHashMap so the order survives.
36. Top K most frequent elements
Input: [1, 1, 1, 2, 2, 3, 4, 4, 4, 4], k = 2 → Output: [4, 1]
Same as 35, but keep only the keys of the first k entries:
int k = 2;
List<Integer> topK = Stream.of(1, 1, 1, 2, 2, 3, 4, 4, 4, 4)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.sorted(Map.Entry.<Integer, Long>comparingByValue().reversed())
.limit(k)
.map(Map.Entry::getKey)
.toList();
// [4, 1] (4 appears 4 times, 1 appears 3 times)
Follow-up: this sorts every distinct value, O(n log n). For huge inputs, a PriorityQueue of size k does it in O(n log k). Mention it; you rarely need to code it in a stream round.
Salary puzzles
37. Second highest salary, and the Nth
Output: 1800000.0 (Asha’s)
The single most asked stream question in Java interviews.
double secondHighest = employees.stream()
.map(Employee::salary)
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst()
.orElseThrow();
// 1800000.0
Step by step: take the salaries, remove duplicates (otherwise two people on the top salary would make the “second highest” equal the highest), sort high to low, skip one, take the next.
Nth highest: change skip(1) to skip(n - 1), and return an Optional because there might not be N distinct salaries:
int n = 4;
Optional<Double> nth = employees.stream()
.map(Employee::salary)
.distinct()
.sorted(Comparator.reverseOrder())
.skip(n - 1)
.findFirst();
// Optional[1200000.0]
Follow-up: “Who earns it?” Filter the employees by that salary. Since Ravi and Priya tie, you get both:
List<String> who = employees.stream()
.filter(e -> e.salary() == nth.get())
.map(Employee::name)
.toList();
// [Ravi, Priya]
(Comparing doubles with == is fine here because both values come straight from the same data. For money in real code, use BigDecimal or whole paise in a long.)
38. Count employees in each department
Map<String, Long> countByDept = employees.stream()
.collect(Collectors.groupingBy(Employee::department, TreeMap::new, Collectors.counting()));
// {Engineering=3, Finance=1, HR=2, Sales=2}
counting() returns a Long, not an Integer. If the interviewer wants Integer, use Collectors.summingInt(e -> 1).
39. Average salary per department
Map<String, Double> avgByDept = employees.stream()
.collect(Collectors.groupingBy(
Employee::department,
TreeMap::new,
Collectors.averagingDouble(Employee::salary)));
// {Engineering=1400000.0, Finance=2100000.0, HR=775000.0, Sales=1100000.0}
Swap the downstream to answer related questions with no other change:
| Question | Downstream collector |
|---|---|
| total salary per department | Collectors.summingDouble(Employee::salary) |
| youngest per department | Collectors.minBy(Comparator.comparingInt(Employee::age)) |
| all stats per department | Collectors.summarizingDouble(Employee::salary) |
40. Department with the most employees
Output: Engineering
Count per department (puzzle 38), then find the entry with the biggest value:
String biggestDept = employees.stream()
.collect(Collectors.groupingBy(Employee::department, Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElseThrow();
// Engineering
max(comparator) returns an Optional, because the stream could be empty. .map(Map.Entry::getKey) reaches inside the Optional to get just the name.
41. Name of the highest-paid employee in each department
Problem 32 gave you Map<String, Employee>. Now the interviewer wants Map<String, String>, the names only:
Map<String, String> topEarnerByDept = employees.stream()
.collect(Collectors.groupingBy(
Employee::department,
TreeMap::new,
Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparingDouble(Employee::salary)),
opt -> opt.get().name())));
// {Engineering=Asha, Finance=Arjun, HR=Meena, Sales=Kiran}
collectingAndThen runs maxBy, then hands its Optional<Employee> to your function, which unwraps it and takes the name.
42. Employee names per department, as one string
Map<String, String> namesByDept = employees.stream()
.collect(Collectors.groupingBy(
Employee::department,
TreeMap::new,
Collectors.mapping(Employee::name, Collectors.joining(", "))));
// {Engineering=Asha, Ravi, Priya, Finance=Arjun, HR=Meena, Fatima, Sales=John, Kiran}
mapping(f, downstream) changes each element with f before passing it to the next collector. Here it turns employees into names, and joining glues the names together.
joining has a second form with a prefix and suffix:
String all = employees.stream()
.map(Employee::name)
.collect(Collectors.joining(", ", "[", "]"));
// [Asha, Ravi, Meena, John, Priya, Kiran, Fatima, Arjun]
43. Split employees by salary: above 10 lakh or not
partitioningBy is groupingBy with exactly two buckets, true and false:
Map<Boolean, List<String>> bySalary = employees.stream()
.collect(Collectors.partitioningBy(
e -> e.salary() > 1_000_000,
Collectors.mapping(Employee::name, Collectors.toList())));
// {false=[Meena, John, Fatima], true=[Asha, Ravi, Priya, Kiran, Arjun]}
partitioningBy vs groupingBy(e -> e.salary() > 1_000_000): the results look alike, but partitioningBy always has both keys. If nobody earned over 10 lakh, partitioningBy still gives you true=[], while groupingBy would have no true key at all, and map.get(true) would be null. That difference is a favourite follow-up question.
It takes downstream collectors too:
Map<Boolean, Long> over35 = employees.stream()
.collect(Collectors.partitioningBy(e -> e.age() >= 35, Collectors.counting()));
// {false=4, true=4}
Transforming puzzles
44. Flatten a list of lists
Input: [[5, 1], [3, 4, 1], [2, 5]] → Output: [1, 2, 3, 4, 5], unique and sorted
flatMap turns each element into a stream, then joins all those streams into one:
List<List<Integer>> nested = List.of(List.of(5, 1), List.of(3, 4, 1), List.of(2, 5));
List<Integer> flat = nested.stream()
.flatMap(List::stream)
.distinct()
.sorted()
.toList();
// [1, 2, 3, 4, 5]
map vs flatMap, the one-line answer: map turns one element into one element, so a list of lists stays a stream of lists. flatMap turns one element into many, and flattens them into a single stream.
Same idea with sentences, getting every distinct word:
List<String> words = List.of("java is fun", "streams are fun").stream()
.flatMap(s -> Arrays.stream(s.split(" ")))
.distinct()
.toList();
// [java, is, fun, streams, are]
45. The toMap duplicate-key trap
Question: “Make a map from department to employee name.”
The obvious answer crashes:
Map<String, String> m = employees.stream()
.collect(Collectors.toMap(Employee::department, Employee::name));
// IllegalStateException: Duplicate key Engineering
// (attempted merging values Asha and Ravi)
Three employees share the key Engineering, and toMap doesn’t know which name to keep, so it throws. Fix it with the third argument, a merge function, which says what to do on a clash:
Map<String, String> m = employees.stream()
.collect(Collectors.toMap(
Employee::department,
Employee::name,
(first, second) -> first + ", " + second, // join the names
TreeMap::new));
// {Engineering=Asha, Ravi, Priya, Finance=Arjun, HR=Meena, Fatima, Sales=John, Kiran}
Other merge functions you might want: (a, b) -> a keeps the first, (a, b) -> b keeps the last. This trap is asked a lot because it shows whether you’ve used toMap on real data. (toMap also throws a NullPointerException if any value is null.)
46. Reverse each word, and reverse the word order
Input: "java is fun"
String s = "java is fun";
// each word reversed: "avaj si nuf"
String eachReversed = Arrays.stream(s.split(" "))
.map(w -> new StringBuilder(w).reverse().toString())
.collect(Collectors.joining(" "));
// word order reversed: "fun is java"
String orderReversed = Arrays.stream(s.split(" "))
.reduce((a, b) -> b + " " + a)
.orElse("");
The second one uses reduce, which combines all elements into one, two at a time: "java" and "is" become "is java", then that and "fun" become "fun is java". Without streams, Collections.reverse on a list of the words is just as good, and easier to read:
List<String> words = Arrays.asList(s.split(" "));
Collections.reverse(words);
String.join(" ", words); // "fun is java"
47. Group anagrams with streams
Problem 18 in one pipeline:
List<List<String>> groups = new ArrayList<>(
Stream.of("eat", "tea", "tan", "ate", "nat", "bat")
.collect(Collectors.groupingBy(
w -> w.chars().sorted()
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString(),
LinkedHashMap::new,
Collectors.toList()))
.values());
// [[eat, tea, ate], [tan, nat], [bat]]
The key function sorts the word’s characters and builds them back into a string. The chars().sorted().collect(StringBuilder::new, ...) part is a mouthful; in an interview it’s fine to pull it out into a small helper:
static String sortLetters(String w) {
char[] c = w.toCharArray();
Arrays.sort(c);
return new String(c);
}
// ... .collect(Collectors.groupingBy(Main::sortLetters, LinkedHashMap::new, Collectors.toList()))
A readable helper beats a clever one-liner. Interviewers agree.
48. Sum of squares of even numbers, with reduce
Input: 1 to 6 → Output: 56 (4 + 16 + 36)
int sum = IntStream.rangeClosed(1, 6)
.filter(x -> x % 2 == 0)
.map(x -> x * x)
.sum();
// 56
With reduce instead of sum(), which interviewers sometimes ask for to check you know it:
int sum = Stream.of(1, 2, 3, 4, 5, 6)
.filter(x -> x % 2 == 0)
.map(x -> x * x)
.reduce(0, Integer::sum);
// 56
reduce(0, Integer::sum) means: start at 0, and keep adding the next element. The 0 is called the identity: the value that changes nothing (0 for adding, 1 for multiplying).
49. Check a palindrome with IntStream
Input: "madam" → true, "java" → false
String s = "madam";
boolean isPalindrome = IntStream.range(0, s.length() / 2)
.allMatch(i -> s.charAt(i) == s.charAt(s.length() - 1 - i));
This is the two-pointer idea from Phase 1 without the pointers: for each i in the first half, compare it with its mirror position. allMatch stops as soon as one comparison fails. Its friends are anyMatch (is at least one true?) and noneMatch (is none true?).
The one-liner everyone knows also works: new StringBuilder(s).reverse().toString().equals(s).
50. Longest word, and words grouped by length
Input: "streams make java code short and clear"
String sentence = "streams make java code short and clear";
String longest = Arrays.stream(sentence.split(" "))
.max(Comparator.comparingInt(String::length))
.orElse("");
// streams
Map<Integer, List<String>> byLength = Arrays.stream(sentence.split(" "))
.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
// {3=[and], 4=[make, java, code], 5=[short, clear], 7=[streams]}
On a tie, which word does max return? The first of the longest words it meets, because it only swaps when the next one is strictly bigger. If the interviewer wants all the longest words, use the grouped map: byLength.lastEntry().getValue() gives the list for the biggest length, since a TreeMap keeps its keys sorted.
Stream traps interviewers love to ask about
1. A stream can only be used once.
Stream<String> st = Stream.of("a", "b");
st.count();
st.count(); // IllegalStateException: stream has already been operated upon or closed
Make a new stream from the source each time: list.stream().
2. toList() gives you a list you can’t change.
List<String> a = Stream.of("x").toList();
a.add("y"); // UnsupportedOperationException
List<String> b = Stream.of("x").collect(Collectors.toList());
b.add("y"); // fine
3. Nothing runs without a terminal operation.
Stream.of("x", "y").peek(System.out::println).map(String::toUpperCase);
// prints nothing: there's no terminal operation, so the pipeline never runs
4. Optional.get() on an empty Optional throws. Prefer orElse, orElseThrow or ifPresent unless you’re sure, as in puzzle 41, that it can’t be empty.
5. Side effects inside lambdas. Changing an outside list or set from inside filter or map works in a simple stream, but breaks with .parallel(). Collect results with a collector instead.
6. groupingBy with no map argument gives a HashMap. If the expected output is in a particular order, pass TreeMap::new (sorted) or LinkedHashMap::new (first appearance).
7. Streams aren’t always better. For a simple loop with a break, or code that changes several variables at once, a plain for loop is often clearer. Saying “I’d use a loop here, and here’s why” is a mature answer, not a weak one.
You’ve finished the plan
That’s all 50 problems. Look back at the shape of the journey:
- Phases 1 and 2 taught loops, two pointers and counting.
- Phases 3 and 4 gave you the collections to count and group with.
- Phases 5 and 6 added ordering: comparators, stacks and queues.
- Phases 7 and 8 said all of it again, shorter, with streams.
Now do what the roadmap said for the last two days: go back to problem 1 and redo the whole list from a blank page, 10 minutes each. The ones you get stuck on are your real study list for the week before the interview.
For that redo, download the free Java Coding Interview Workbook PDF. It lists every problem without answers, adds six bonus problems, and ends with cheat sheets and a one-line-per-problem revision list.
Comments