Skip to lesson

Practice: Write-the-Stream Coding Questions

"Write this with streams" is a standard coding round: second highest, duplicates, character counts, group and average. The interviewer watches whether you recognise the pattern, write one step per line, and say the edge cases aloud.

Round 1: second highest, duplicates, frequency, first non-repeated

The sort-skip pattern finds the Nth largest value: distinct(), sorted(reverseOrder()), skip(n - 1), findFirst(). The distinct step handles ties, and the Optional handles a list that is too short.

Run the second-highest pipeline and two ways to find duplicates, then the character frequency and the first non-repeated character.

Example 1 · Second highest salary and two ways to find duplicates

SecondHighestDuplicatesDemo.javaJava
import java.util.Comparator;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.Set;import java.util.function.Function;import java.util.stream.Collectors;
public class SecondHighestDuplicatesDemo {    static Optional<Integer> secondHighest(List<Integer> salaries) {        return salaries.stream()                .distinct()                .sorted(Comparator.reverseOrder())                .skip(1)                .findFirst();    }
    public static void main(String[] args) {        List<Integer> salaries = List.of(42000, 65000, 58000, 65000, 39000);        System.out.println("Second highest: " + secondHighest(salaries).orElse(-1));        System.out.println("Only one salary: " + secondHighest(List.of(50000, 50000)).orElse(-1));
        List<String> rolls = List.of("R12", "R07", "R12", "R33", "R07", "R12");
        Set<String> seen = new HashSet<>();        List<String> dupsBySet = rolls.stream()                .filter(r -> !seen.add(r))     // add returns false for a repeat                .distinct()                .toList();        System.out.println("Duplicates (Set trick): " + dupsBySet);
        Map<String, Long> counts = rolls.stream()                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));        List<String> dupsByCount = counts.entrySet().stream()                .filter(e -> e.getValue() > 1)                .map(Map.Entry::getKey)                .sorted()                .toList();        System.out.println("Duplicates (counting): " + dupsByCount);    }}
Output
Second highest: 58000
Only one salary: -1
Duplicates (Set trick): [R12, R07]
Duplicates (counting): [R07, R12]

What this code does

  • With 65000 appearing twice, distinct() makes 58000 the true second highest. A list with only one distinct value gives an empty Optional, shown as -1.
  • The Set trick keeps duplicates in the order they repeat (R12, then R07). The counting version sorts the keys because the HashMap from groupingBy has no order.

Example 2 · Character frequency and the first non-repeated character

FrequencyFirstUniqueDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;import java.util.function.Function;import java.util.stream.Collectors;
public class FrequencyFirstUniqueDemo {    public static void main(String[] args) {        String word = "programming";
        Map<Character, Long> freq = word.chars()                .mapToObj(c -> (char) c)                .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));        System.out.println("Frequency: " + freq);
        Character firstUnique = freq.entrySet().stream()                .filter(e -> e.getValue() == 1)                .map(Map.Entry::getKey)                .findFirst()                .orElse(null);        System.out.println("First non-repeated: " + firstUnique);
        Character firstRepeated = freq.entrySet().stream()                .filter(e -> e.getValue() > 1)                .map(Map.Entry::getKey)                .findFirst()                .orElse(null);        System.out.println("First repeated (in first-seen order): " + firstRepeated);    }}
Output
Frequency: {p=1, r=2, o=1, g=2, a=1, m=2, i=1, n=1}
First non-repeated: p
First repeated (in first-seen order): r

What this code does

  • LinkedHashMap::new keeps the letters in the order they first appear, so the first entry with count 1 is the first non-repeated character: p.
  • The same map answers the follow-up "first repeated character": the first entry with count above 1 is r.

Say why each step is there: distinct handles a tie for the top value, and findFirst returns an Optional because there may be no second value. Duplicates use either a Set whose add returns false for a repeat, or groupingBy with counting() and a filter on count > 1. The first non-repeated character is the first entry with count 1 in a LinkedHashMap frequency map, and interviewers often ask exactly that follow-up. Revise: distinct and sorted (opens in a new tab) and groupingBy basics (opens in a new tab).

Say these aloud:

  • Edge cases: empty list, all equal values, one element.
  • Complexity: sorting is O(n log n); the frequency map is O(n).
  • The Set trick uses a side effect, so it is not safe on a parallel stream.
  • For "Nth highest", change skip(1) to skip(n - 1).

Order of execution

Second highest salary

Tap the steps in the order the pipeline runs them.

Optional<Integer> second = salaries.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst();

Round 2: group employees by department and average salary

The group-then-aggregate pattern is groupingBy(key, downstream). The key says which group an element joins, and the downstream collector (averagingDouble, counting, maxBy, mapping) says what each group becomes.

Group employees by department and average the salaries. Then swap the downstream collector to answer each follow-up.

Example 3 · Department averages, headcount and follow-ups

DeptAverageDemo.javaJava
import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.TreeMap;import java.util.stream.Collectors;
public class DeptAverageDemo {    record Employee(String name, String dept, double salary) {}
    public static void main(String[] args) {        List<Employee> staff = List.of(                new Employee("Anil", "IT", 72000), new Employee("Bina", "HR", 41000),                new Employee("Chirag", "IT", 81000), new Employee("Deepa", "HR", 47000),                new Employee("Esha", "Sales", 38000), new Employee("Farhan", "IT", 66000));
        Map<String, Double> avg = staff.stream()                .collect(Collectors.groupingBy(Employee::dept, TreeMap::new,                        Collectors.averagingDouble(Employee::salary)));        avg.forEach((d, a) -> System.out.printf("%-6s average %.2f%n", d, a));
        Map<String, Long> headcount = staff.stream()                .collect(Collectors.groupingBy(Employee::dept, TreeMap::new, Collectors.counting()));        System.out.println("Headcount: " + headcount);
        Optional<Map.Entry<String, Double>> best = avg.entrySet().stream()                .max(Map.Entry.comparingByValue());        System.out.println("Highest average: " + best.map(Map.Entry::getKey).orElse("none"));
        double companyAvg = staff.stream().mapToDouble(Employee::salary).average().orElse(0);        List<String> aboveCompanyAvg = staff.stream()                .filter(e -> e.salary() > companyAvg)                .sorted(Comparator.comparingDouble(Employee::salary).reversed())                .map(Employee::name)                .toList();        System.out.println("Above company average: " + aboveCompanyAvg);    }}
Output
HR     average 44000.00
IT     average 73000.00
Sales  average 38000.00
Headcount: {HR=2, IT=3, Sales=1}
Highest average: IT
Above company average: [Chirag, Anil, Farhan]

What this code does

  • averagingDouble gives a Double average per department; printf("%.2f") formats it. A TreeMap keeps HR, IT, Sales in order.
  • The company average (57500) is computed once before the pipeline, then used in filter. The highest department average is found with max(Map.Entry.comparingByValue()).

Swap the downstream collector for the follow-ups: counting() for headcount, summingDouble for payroll, maxBy(comparing...) for the top earner, mapping(Employee::name, toList()) for names. Add TreeMap::new when the output order matters.

Compute a company-wide value such as the overall average once, outside the lambda, rather than inside filter where it would be recomputed for every employee. Revise: Downstream collectors (opens in a new tab).

Fix the error

Fix the grouping types

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

Count the employees in each department.

import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import java.util.List;
import java.util.Map;
public class GFix1 {
record Emp(String name, String dept) {}
public static void main(String[] args) {
List<Emp> staff = List.of(new Emp("Anil", "IT"), new Emp("Bina", "HR"));
Map<String, Integer> n = staff.stream().collect(groupingBy(Emp::dept, counting()));
System.out.println(n);
}
}

Error

GFix1.java:9: error: incompatible types: inference variable D has incompatible equality constraints Integer,Long
        Map<String, Integer> n = staff.stream().collect(groupingBy(Emp::dept, counting()));
                                                       ^

Round 3: convert a loop to a stream and back

A loop-to-stream rewrite maps each part of a loop to a stream step: the if becomes filter, the value you add becomes map, Collections.sort becomes sorted, and the result list becomes toList().

Rewrite one loop as a stream, then prove both give the same answer by comparing their outputs.

Example 4 · The same logic as a loop and as a stream

LoopToStreamDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class LoopToStreamDemo {    record Order(String id, String city, int amount) {}
    static List<String> withLoop(List<Order> orders) {        List<String> result = new ArrayList<>();        for (Order o : orders) {            if (o.city().equals("Pune") && o.amount() >= 500) {                result.add(o.id().toLowerCase());            }        }        Collections.sort(result);        return result;    }
    static List<String> withStream(List<Order> orders) {        return orders.stream()                .filter(o -> o.city().equals("Pune"))                .filter(o -> o.amount() >= 500)                .map(o -> o.id().toLowerCase())                .sorted()                .toList();    }
    public static void main(String[] args) {        List<Order> orders = List.of(                new Order("ORD-9", "Pune", 750), new Order("ORD-2", "Delhi", 900),                new Order("ORD-5", "Pune", 300), new Order("ORD-1", "Pune", 1200));        System.out.println("Loop:   " + withLoop(orders));        System.out.println("Stream: " + withStream(orders));        System.out.println("Same?   " + withLoop(orders).equals(withStream(orders)));
        int total = 0;        for (Order o : orders) {            total += o.amount();        }        int streamTotal = orders.stream().mapToInt(Order::amount).sum();        System.out.println("Totals: " + total + " " + streamTotal);    }}
Output
Loop:   [ord-1, ord-9]
Stream: [ord-1, ord-9]
Same?   true
Totals: 3150 3150

What this code does

  • The loop's if with two conditions became two filter steps, result.add(...) became map, and Collections.sort became sorted(). Comparing the two lists proves the rewrite.
  • A running total with += becomes mapToInt(Order::amount).sum(), which avoids boxing and needs no mutable variable.

Going back to a loop is also asked: "How would you write this without streams?" A loop is the better choice when you need break with complex conditions, checked exceptions, or index access to neighbours; a stream is clearer for filter-map-collect pipelines. Revise: Loops versus streams (opens in a new tab).

Find the bug

Find the rewrite bug

Each stream should replace a loop. Tap the wrong line, then check the fix.

Collect the ids of orders of 500 or more.

Round 1 of 3

Round 4: predict the output on laziness and Optional

The predict-the-output rules are four checks: no terminal operation means nothing runs; elements pass through all steps one at a time; short-circuiting stops early; and orElse evaluates its argument even when a value exists.

Four rules solve most predict-the-output puzzles. Run the set below and check each answer against a rule.

Example 5 · Predict-the-output set: five classic questions

PredictSetDemo.javaJava
import java.util.List;import java.util.Optional;import java.util.stream.Stream;
public class PredictSetDemo {    static String fallback() {        System.out.print("[fallback] ");        return "none";    }
    public static void main(String[] args) {        // P1: laziness with findFirst        Stream.of("cat", "lion", "tiger", "ox")                .filter(s -> { System.out.print("F:" + s + " "); return s.length() > 3; })                .map(s -> { System.out.print("M:" + s + " "); return s.toUpperCase(); })                .findFirst()                .ifPresent(s -> System.out.println("=> " + s));
        // P2: orElse vs orElseGet        System.out.println("P2a " + Optional.of("cash").orElse(fallback()));        System.out.println("P2b " + Optional.of("cash").orElseGet(PredictSetDemo::fallback));
        // P3: map on an empty Optional        Optional<String> none = Optional.empty();        System.out.println("P3 " + none.map(String::length).orElse(0));
        System.out.println("P4 " + List.of(3, 3, 1, 2, 1, 5).stream().distinct().limit(3).toList());
        System.out.println("P5 " + Stream.<Integer>empty().reduce(10, Integer::sum));    }}
Output
F:cat F:lion M:lion => LION
[fallback] P2a cash
P2b cash
P3 0
P4 [3, 1, 2]
P5 10

What this code does

  • P1: cat fails the filter, lion passes and is mapped, and findFirst stops, so tiger and ox are never checked. P2: orElse(fallback()) runs fallback (printed before the line itself), orElseGet does not.
  • P3: map on an empty Optional is skipped, so orElse(0) gives 0. P4: distinct keeps first occurrences in order, then limit(3). P5: an empty stream reduces to the identity, 10.

Two more appear in written tests: map on an empty Optional never calls the function, and reduce with an identity on an empty stream returns the identity. Revise: Lazy evaluation (opens in a new tab).

Predict the output

Predict the output

Read each program and pick what it prints.

Round 1 of 4

A filter, a map and findFirst, with a log.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class PrA {
public static void main(String[] args) {
List<String> log = new ArrayList<>();
Stream.of("cat", "lion", "tiger", "ox")
.filter(s -> {
log.add("F:" + s);
return s.length() > 3;
})
.map(s -> {
log.add("M:" + s);
return s.toUpperCase();
})
.findFirst();
System.out.println(log);
}
}

Next step

Check your understanding

12 quick questions