35 Java Streams API Questions for SDE-2 Interviews
The definitive 2026 guide to 35 essential Java Streams coding and conceptual interview questions for SDE-2 and Senior Backend roles—with production code, edge cases, and collector architectures.
Vivek Adarsh
Founder & Systems Architect, Veltoryx Technologies · Published November 5, 2026
In modern Software Development Engineer II (SDE-2) and Senior Java Backend interviews, the Java 8+ Stream API is the single most tested topic in live coding and machine coding rounds.
Interviewers do not just want to see if you know how to write a simple .filter() or .map(). They test whether you understand:
- Edge case and null resilience: What happens when duplicate keys collide in a map? What if the list is empty?
- Algorithmic efficiency: Are you inadvertently doing an
O(n²)lookup inside a stream filter? - Internal mechanics: Do you know how
Spliterator,Sinkpipelines, andForkJoinPoolwork under the hood? - Stream vs Loop tradeoffs: When does a traditional loop outperform a stream by 5x?
Below is the complete, production-tested breakdown of 35 essential Java Streams questions—split into 20 live coding challenges, 15 deep conceptual questions, and an SDE-2 Architectural Masterclass.
The Common Domain Model: Employee & Department
To keep the coding examples consistent and realistic, we will use this standard Employee record across all problem solutions:
public record Employee(
int id,
String name,
String department,
double salary,
int age
) {}Part 1: Coding Questions (20 Scenarios)
1. Find the second-highest salary
To find the second-highest salary cleanly, sort salaries in descending order, skip duplicates with distinct(), and skip the first (highest) element:
public static Optional<Double> getSecondHighestSalary(List<Employee> employees) {
return employees.stream()
.map(Employee::salary)
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst();
}2. Find the highest salary in each department
Group by department name, then use Collectors.collectingAndThen with Collectors.maxBy to extract the employee or unwrap the Optional:
public static Map<String, Employee> getHighestPaidByDepartment(List<Employee> employees) {
return employees.stream()
.collect(Collectors.groupingBy(
Employee::department,
Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparingDouble(Employee::salary)),
Optional::get
)
));
}3. Find duplicate elements in a list
Use a HashSet.add() check inside .filter(). Because Set.add() returns false if an element is already present, inverting the check identifies duplicates:
public static <T> Set<T> findDuplicates(List<T> list) {
Set<T> seen = new HashSet<>();
return list.stream()
.filter(item -> !seen.add(item))
.collect(Collectors.toSet());
}4. Find the first non-repeated character in a string
Count character frequencies while preserving insertion order using LinkedHashMap, then find the first character with a frequency of 1:
public static Optional<Character> findFirstNonRepeated(String input) {
return input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new, // Mandatory: preserves character order!
Collectors.counting()
))
.entrySet().stream()
.filter(entry -> entry.getValue() == 1L)
.map(Map.Entry::getKey)
.findFirst();
}5. Count character frequency in a string
public static Map<Character, Long> countCharFrequency(String input) {
return input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
));
}6. Count word frequency in a sentence
Split the sentence by whitespace regex (\\s+), filter out blank tokens, and group:
public static Map<String, Long> countWordFrequency(String sentence) {
if (sentence == null || sentence.isBlank()) return Collections.emptyMap();
return Arrays.stream(sentence.trim().toLowerCase().split("\\s+"))
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
));
}7. Find the first repeated character
public static Optional<Character> findFirstRepeated(String input) {
Set<Character> seen = new HashSet<>();
return input.chars()
.mapToObj(c -> (char) c)
.filter(c -> !seen.add(c)) // First character that fails insertion
.findFirst();
}8. Find employees earning above average salary
Compute the average first with Collectors.averagingDouble, then filter in a second pass:
public static List<Employee> getAboveAverageEarners(List<Employee> employees) {
double avgSalary = employees.stream()
.collect(Collectors.averagingDouble(Employee::salary));
return employees.stream()
.filter(e -> e.salary() > avgSalary)
.toList();
}9. Group employees by department
public static Map<String, List<Employee>> groupByDept(List<Employee> employees) {
return employees.stream()
.collect(Collectors.groupingBy(Employee::department));
}10. Sort employees by salary (Ascending and Descending)
// Ascending order:
List<Employee> asc = employees.stream()
.sorted(Comparator.comparingDouble(Employee::salary))
.toList();
// Descending order with secondary tie-breaker by name:
List<Employee> desc = employees.stream()
.sorted(Comparator.comparingDouble(Employee::salary).reversed()
.thenComparing(Employee::name))
.toList();11. Find maximum and minimum elements
Optional<Employee> highestPaid = employees.stream()
.max(Comparator.comparingDouble(Employee::salary));
Optional<Employee> lowestPaid = employees.stream()
.min(Comparator.comparingDouble(Employee::salary));12. Find the top 3 highest salaries
public static List<Double> getTop3Salaries(List<Employee> employees) {
return employees.stream()
.map(Employee::salary)
.distinct()
.sorted(Comparator.reverseOrder())
.limit(3)
.toList();
}13. Find the Nth highest salary
Generalize Question 1 using .skip(n - 1).findFirst():
public static Optional<Double> getNthHighestSalary(List<Employee> employees, int n) {
if (n <= 0) return Optional.empty();
return employees.stream()
.map(Employee::salary)
.distinct()
.sorted(Comparator.reverseOrder())
.skip(n - 1)
.findFirst();
}14. Partition numbers into even and odd
Use Collectors.partitioningBy which always returns a Map<Boolean, List<T>> with exactly two keys: true and false:
public static Map<Boolean, List<Integer>> partitionEvenOdd(List<Integer> numbers) {
return numbers.stream()
.collect(Collectors.partitioningBy(num -> num % 2 == 0));
}15. Calculate salary sum and average
Use Collectors.summarizingDouble to compute count, sum, min, average, and max in a single pass:
DoubleSummaryStatistics stats = employees.stream()
.collect(Collectors.summarizingDouble(Employee::salary));
System.out.println("Total Sum: " + stats.getSum());
System.out.println("Average : " + stats.getAverage());
System.out.println("Max : " + stats.getMax());16. Convert List<Employee> into Map<Id, Employee>
Always supply a merge function to handle potential duplicate IDs without throwing IllegalStateException:
public static Map<Integer, Employee> convertToMap(List<Employee> employees) {
return employees.stream()
.collect(Collectors.toMap(
Employee::id,
Function.identity(),
(existing, replacement) -> existing // Merge rule: keep existing on duplicate ID
));
}17. Find employees whose names start with a given character
public static List<Employee> findByNamePrefix(List<Employee> employees, char prefix) {
String prefixStr = String.valueOf(prefix).toLowerCase();
return employees.stream()
.filter(e -> e.name() != null && e.name().toLowerCase().startsWith(prefixStr))
.toList();
}18. Find the longest string in a list
public static Optional<String> findLongestString(List<String> strings) {
return strings.stream()
.max(Comparator.comparingInt(String::length));
}19. Remove duplicates using Streams
// Natural duplicates:
List<Integer> unique = numbers.stream().distinct().toList();
// Deduplicate by custom property (e.g., unique by department):
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
List<Employee> uniqueByDept = employees.stream()
.filter(distinctByKey(Employee::department))
.toList();20. Find common elements between two lists
Convert the second list to a HashSet first for O(1) lookups, avoiding an O(n × m) nested loop:
public static <T> List<T> findCommonElements(List<T> list1, List<T> list2) {
Set<T> lookup = new HashSet<>(list2); // O(m) preparation
return list1.stream()
.filter(lookup::contains) // O(1) membership check
.distinct()
.toList();
}Part 2: Conceptual Questions (15 Deep-Dives)
21. Stream vs Collection
- Collection: An in-memory data structure that holds elements. Every element is stored and computed eagerly before the collection exists. Collections are about data storage.
- Stream: A pipeline of computations that moves elements from a source through intermediate steps to a terminal destination. Streams do not store elements and do not modify the backing source. Streams are about data transformation.
22. Intermediate vs Terminal Operations
- Intermediate Operations (
filter,map,sorted): Return a newStream<T>. They are lazy and perform no work until a terminal operation is called. They can be chained infinitely. - Terminal Operations (
collect,forEach,reduce,count): Consume the stream pipeline, produce a final non-stream result (or side effect), and close the stream.
23. map() vs flatMap()
map(Function<T, R>): Performs a1 → 1mapping. It takes an input element and transforms it into a single output element.flatMap(Function<T, Stream<R>>): Performs a1 → Nmapping followed by flattening. Each element produces a sub-stream of values, and all sub-streams are merged into a single continuous stream.
24. filter() vs map()
filter(Predicate<T>): Selects elements based on a boolean condition. It changes the quantity of elements in the stream (0 to N), but never changes their type.map(Function<T, R>): Transforms every element in the stream. It keeps the quantity identical, but may change the type (T → R).
25. map() vs peek()
map()is designed for data transformation where the return value is passed downstream.peek(Consumer<T>)is strictly designed for debugging and non-interfering side-effects (e.g., logging an element as it flows past).
26. findFirst() vs findAny()
findFirst(): Deterministically returns the very first element in the stream according to its encounter order.findAny(): Returns any arbitrary matching element. In aparallelStream(),findAny()is significantly faster because worker threads can return the moment any thread encounters a match without synchronizing on encounter order.
27. reduce() vs collect()
reduce(BinaryOperator<T>): Designed for immutable reduction. It takes two values and produces a new combined value (e.g., summing integers:a + b). Because it creates a new object on each step, using it to build collections causes catastrophicO(n²)memory churn.collect(Collector): Designed for mutable reduction. It accumulates elements into a mutable container (like anArrayListorStringBuilder) in-place with high performance.
28. groupingBy() vs partitioningBy()
groupingBy(Function<T, K>): Classifies stream elements into an arbitrary number of groups based on any key typeK(Map<K, List<T>>).partitioningBy(Predicate<T>): A specialized boolean classification. It always partitions elements into aMap<Boolean, List<T>>with exactly two buckets:trueandfalse.
29. What is lazy evaluation?
Lazy evaluation means that intermediate operations (filter, map, sorted) are not executed when they are declared. Instead, Java records them as a linked pipeline of Sink stages.
Computation only begins when a terminal operation is called. This allows the JVM to fuse multiple operations into a single pass and apply short-circuiting (e.g., stopping immediately once findFirst() finds a match).
30. Can a Stream be reused?
No. A Java Stream can only be operated on (invoking a terminal operation) once. Once a terminal operation finishes, the stream is considered consumed and closed.
Attempting to call another operation on a closed stream throws:
java.lang.IllegalStateException: stream has already been operated upon or closed.
31. Sequential vs Parallel Streams
- Sequential Stream (
stream()): Processes all elements on a single calling thread in predictable encounter order. - Parallel Stream (
parallelStream()): Uses aSpliteratorto divide elements recursively into sub-tasks and executes them concurrently using the shared JVM-wideForkJoinPool.commonPool().
32. When should you avoid parallelStream()?
You should avoid parallelStream() in:
- Web APIs & Servlet Threads (Tomcat / Spring Boot): Your server already handles concurrency by assigning worker threads per HTTP request. Running parallel streams inside request threads creates thread contention and starves the shared
ForkJoinPool.commonPool(). - Blocking I/O Operations: Calling database queries, external REST endpoints, or disk I/O in a parallel stream blocks carrier threads, halting unrelated parallel streams across the entire JVM.
- Small Collections (
N × Q < 10,000): Thread splitting and merging overhead exceeds the cost of sequential execution for small datasets. - Operations sensitive to ordering:
findFirst(),limit(), andskip()require expensive inter-thread synchronization in parallel mode.
33. How does distinct() work internally?
For an un-ordered stream, distinct() uses an internal HashSet to test whether an element has been seen before.
If the stream is ordered and backed by a sorted structure, the JVM can optimize distinct() by comparing consecutive elements rather than maintaining a full hash set.
34. How does sorted() work internally?
Unlike stateless operations (filter, map), sorted() is a stateful intermediate operation.
It cannot pass elements downstream one by one. It must buffer every single element in the stream into an internal array, sort it using Arrays.sort() (TimSort for objects), and only then push sorted elements to downstream sinks. On infinite or massive streams, sorted() will exhaust memory and throw OutOfMemoryError.
35. How are exceptions handled in Streams?
Java Streams do not natively handle checked exceptions. If a lambda throws a checked exception (e.g., IOException), the compiler rejects the standard functional interface (Function, Predicate).
The Three Solutions:
- Try-Catch Wrapper Inside Lambda: Catch the checked exception and rethrow it as an unchecked
RuntimeException. - Generic Throwing Function Adapter: Write a higher-order utility that wraps checked exceptions cleanly.
- Either / Result Monad: Return an
Either<Exception, Result>object downstream to handle errors functionally without terminating the stream.
@FunctionalInterface
public interface ThrowingFunction<T, R, E extends Exception> {
R apply(T t) throws E;
static <T, R> Function<T, R> unchecked(ThrowingFunction<T, R, ?> f) {
return t -> {
try {
return f.apply(t);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
};
}
}Part 3: SDE-2 Architectural Masterclass
When senior interviewers assess your answers, they look for these five real-world engineering instincts:
1. Primitive Boxing Overhead
Using Stream<Integer> or Stream<Double> forces the JVM to box and unbox millions of primitive values. Always use specialized primitive streams (IntStream, LongStream, DoubleStream):
// BAD: Boxes 1,000,000 Double objects (high heap allocation + GC pause)
double badSum = employees.stream().map(Employee::salary).reduce(0.0, Double::sum);
// GOOD: Zero boxing overhead using DoubleStream
double goodSum = employees.stream().mapToDouble(Employee::salary).sum();2. Streams vs Traditional For-Loops
- Use Streams when: Performing declarative data transformations, filtering, grouping, or chaining cohesive pipelines where readability and immutability are paramount.
- Use For-Loops when: Writing ultra-low latency code with complex break/continue control flows, primitive arrays, or stateful index manipulations where every microsecond of object allocation matters.
Master Modern Java with Veltoryx
Preparing for senior backend interviews requires both coding speed and deep architectural mastery.
Explore our comprehensive interactive curriculum:
- Java Stream API Basics & Pipelines
- FlatMap, Reductions & Sorting
- Java Collectors & Custom Reductions
- Parallel Streams & ForkJoinPool Tuning
- Java Core & Concurrency Masterclass
Looking for companion interview playbooks?
- Java Backend Developer 1st Round Interview: 20 Questions Being Asked in 2026
- Java 8 to Java 21: Top 40 Interview Questions for Senior Software Engineers & Tech Leads
Level up your engineering career with real-world architectural blueprints and interactive visualizers:
Explore Free Developer Tools & Interactive Tracks
Test data structures, format code, and master system design on the Veltoryx platform.
Related Engineering Articles
Java DSA Interview – Complete Methods & Syntax Cheat Sheet
The ultimate quick-reference cheat sheet for Java DSA coding interviews — covering essential Java 8+ syntax, collection methods, and LeetCode problem-solving patterns.
Vivek Adarsh
Nov 24, 2026
Java 8 to Java 21: Top 40 Interview Questions for Senior Software Engineers & Tech Leads
The definitive 2026 guide covering the 40 essential modern Java interview questions across Java 8 through Java 21, concurrency, JVM internals, virtual threads, and production scenarios.
Vivek Adarsh
Nov 5, 2026
Java Backend Developer 1st Round Interview: 20 Questions Being Asked in 2026
A battle-tested guide to the top 20 core Java, JVM, Spring Boot, JPA, and distributed systems questions asked in senior first-round technical interviews in 2026—with code examples, root causes, and production fixes.
Vivek Adarsh
Nov 5, 2026