Java Stream API is one of the most frequently discussed topics in Java developer interviews. Whether you are interviewing for a Senior Java Developer, Technical Lead or Full Stack Developer position, a strong understanding of Streams is essential.
Introduced in Java 8, the Stream API provides a functional approach to processing collections of data. It allows developers to filter, transform, sort, group and aggregate data without writing excessive loops.
However, knowing the syntax of filter(), map() and collect() is not enough for experienced developers.
Interviewers often expect you to solve practical problems involving:
Filtering and transforming collections.
Sorting and finding the highest or second-highest values.
Grouping records using
Collectors.groupingBy().Working with nested collections using
flatMap().Handling duplicate elements.
Using
Optionalcorrectly.Processing employee and transaction data.
Understanding performance and parallel streams.
This guide contains 50 Java Stream API coding interview questions, starting with basic operations and progressing to advanced real-world scenarios.
Java compatibility: Examples are primarily compatible with Java 8 and later. Newer APIs are identified separately.
Table of Contents
Basic Stream API Questions
Filtering and Transformation
Sorting and Finding Elements
Collectors and Grouping
Employee-Based Real-World Problems
flatMap and Nested Collections
String and Character Problems
Advanced Stream API Coding Problems
Important Interview Concepts
Frequently Asked Questions
Section 1: Basic Java Stream API Questions
Q1. Find all even numbers from a list
Problem: Given a list of integers, return only even numbers.
Solution:
List<Integer> numbers = Arrays.asList(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers);Output:
[2, 4, 6, 8, 10]Explanation:
stream()creates a stream from the collection.filter()selects elements satisfying the condition.collect()converts the stream back into a list.
Interview concept: filter() is an intermediate operation and collect() is a terminal operation.
Q2. Find all odd numbers from a list
List<Integer> oddNumbers = numbers.stream()
.filter(n -> n % 2 != 0)
.collect(Collectors.toList());
System.out.println(oddNumbers);Output:
[1, 3, 5, 7, 9]Q3. Find the square of every number
List<Integer> squares = numbers.stream()
.map(n -> n * n)
.collect(Collectors.toList());
System.out.println(squares);Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]Interview concept: map() transforms every element into another value.
Q4. Remove duplicate elements from a list
List<Integer> values = Arrays.asList(
10, 20, 10, 30, 20, 40
);
List<Integer> uniqueValues = values.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(uniqueValues);Output:
[10, 20, 30, 40]Interview concept: distinct() uses equality semantics to identify duplicate elements. For custom objects, implement equals() and hashCode() appropriately.
Q5. Count the number of elements in a list
long count = numbers.stream()
.count();
System.out.println(count);Output:
10Q6. Convert all strings to uppercase
List<String> names = Arrays.asList(
"java", "spring", "kafka"
);
List<String> upperCaseNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(upperCaseNames);Output:
[JAVA, SPRING, KAFKA]Q7. Filter strings starting with a particular character
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("s"))
.collect(Collectors.toList());
System.out.println(filteredNames);Output:
[spring]Q8. Find the longest string in a list
Optional<String> longestName = names.stream()
.max(Comparator.comparingInt(String::length));
longestName.ifPresent(System.out::println);Output:
springInterview concept: max() returns an Optional because the collection may be empty.
Q9. Find the shortest string in a list
Optional<String> shortestName = names.stream()
.min(Comparator.comparingInt(String::length));
shortestName.ifPresent(System.out::println);Output:
javaQ10. Join all strings with a comma separator
String result = names.stream()
.collect(Collectors.joining(", "));
System.out.println(result);Output:
java, spring, kafkaSection 2: Filtering and Transformation
Q11. Find the frequency of each integer
Problem: Count how many times each number appears.
List<Integer> values = Arrays.asList(
1, 2, 2, 3, 3, 3, 4
);
Map<Integer, Long> frequency = values.stream()
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
));
System.out.println(frequency);Output:
{1=1, 2=2, 3=3, 4=1}Explanation:
Function.identity()returns the element itself.groupingBy()groups equal elements.counting()counts the elements in each group.
Q12. Find the frequency of each character in a string
String input = "programming";
Map<Character, Long> characterFrequency =
input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
));
System.out.println(characterFrequency);Output: Character frequencies are grouped into a map.
Q13. Find duplicate elements in a list
Set<Integer> duplicates = values.stream()
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
))
.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
System.out.println(duplicates);Output:
[2, 3]Q14. Find elements appearing exactly once
List<Integer> uniqueElements = values.stream()
.collect(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new,
Collectors.counting()
))
.entrySet()
.stream()
.filter(entry -> entry.getValue() == 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println(uniqueElements);Output:
[1, 4]Q15. Find the second-highest distinct number
Optional<Integer> secondHighest = numbers.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst();
System.out.println(secondHighest.orElse(null));Explanation:
distinct()removes duplicate values.sorted()sorts in descending order.skip(1)skips the highest value.findFirst()returns the next value.
Interview follow-up: What happens when the collection contains fewer than two distinct values?
Answer: The result is an empty Optional.
Q16. Find the Nth highest distinct number
int n = 3;
Optional<Integer> nthHighest = numbers.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.skip(n - 1)
.findFirst();
System.out.println(nthHighest.orElse(null));Important: Validate that n is greater than zero before executing the stream.
Q17. Find the top three highest numbers
List<Integer> topThree = numbers.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.limit(3)
.collect(Collectors.toList());
System.out.println(topThree);Q18. Sort numbers in ascending order
List<Integer> ascending = numbers.stream()
.sorted()
.collect(Collectors.toList());
System.out.println(ascending);Q19. Sort numbers in descending order
List<Integer> descending = numbers.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println(descending);Q20. Sort strings based on their length
List<String> sortedNames = names.stream()
.sorted(Comparator.comparingInt(String::length))
.collect(Collectors.toList());
System.out.println(sortedNames);Interview concept: Comparators allow custom sorting rules without modifying the original objects.
Section 3: Collectors and Grouping
Q21. Find the maximum number in a list
Optional<Integer> maximum = numbers.stream()
.max(Integer::compareTo);
System.out.println(maximum.orElse(null));Q22. Find the minimum number in a list
Optional<Integer> minimum = numbers.stream()
.min(Integer::compareTo);
System.out.println(minimum.orElse(null));Q23. Calculate the sum of all numbers
int sum = numbers.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println(sum);Q24. Calculate the average of all numbers
OptionalDouble average = numbers.stream()
.mapToInt(Integer::intValue)
.average();
System.out.println(
average.isPresent() ? average.getAsDouble() : 0.0
);Interview concept: mapToInt() converts a regular object stream into an IntStream, which provides primitive operations such as sum() and average().
Q25. Partition numbers into even and odd groups
Map<Boolean, List<Integer>> partitioned =
numbers.stream()
.collect(Collectors.partitioningBy(
n -> n % 2 == 0
));
System.out.println(partitioned);Output structure:
{
false=[1, 3, 5, 7, 9],
true=[2, 4, 6, 8, 10]
}Interview concept: partitioningBy() creates exactly two Boolean groups, whereas groupingBy() can create multiple groups.
Q26. Group strings by their length
Map<Integer, List<String>> groupedByLength =
names.stream()
.collect(Collectors.groupingBy(
String::length
));
System.out.println(groupedByLength);Output structure:
{
4=[java],
6=[spring],
5=[kafka]
}Q27. Group employees by department
Assume an Employee class has the following properties:
class Employee {
private int id;
private String name;
private String department;
private double salary;
// Constructor, getters and setters
}Create an employee list:
List<Employee> employees = Arrays.asList(
new Employee(1, "Amit", "IT", 80000),
new Employee(2, "Rahul", "HR", 50000),
new Employee(3, "Priya", "IT", 95000),
new Employee(4, "Neha", "Finance", 70000),
new Employee(5, "Vikas", "HR", 60000)
);Group employees by department:
Map<String, List<Employee>> employeesByDepartment =
employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment
));Interview concept: This is one of the most common real-world groupingBy() interview problems.
Q28. Calculate the average salary of each department
Map<String, Double> averageSalary =
employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.averagingDouble(
Employee::getSalary
)
));
System.out.println(averageSalary);Expected result:
{
IT=87500.0,
HR=55000.0,
Finance=70000.0
}Q29. Find the highest-paid employee in each department
Map<String, Optional<Employee>> highestPaidByDepartment =
employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.maxBy(
Comparator.comparingDouble(
Employee::getSalary
)
)
));Interview concept: maxBy() is a downstream collector. Its result is an Optional<Employee> for each group.
Q30. Find the second-highest-paid employee
Optional<Employee> secondHighestPaid =
employees.stream()
.sorted(
Comparator.comparingDouble(
Employee::getSalary
).reversed()
)
.skip(1)
.findFirst();
secondHighestPaid.ifPresent(employee ->
System.out.println(
employee.getName() + " : " + employee.getSalary()
)
);Important interview distinction: This finds the second employee by salary, not necessarily the second-highest distinct salary. To find the second-highest distinct salary, first find the second salary value using distinct(), then select an employee with that salary.
Section 4: Employee-Based Real-World Problems
Q31. Sort employees by salary in descending order
List<Employee> sortedEmployees = employees.stream()
.sorted(
Comparator.comparingDouble(
Employee::getSalary
).reversed()
)
.collect(Collectors.toList());Q32. Get employee names belonging to the IT department
List<String> itEmployees = employees.stream()
.filter(e -> "IT".equals(e.getDepartment()))
.map(Employee::getName)
.collect(Collectors.toList());
System.out.println(itEmployees);Q33. Count employees in each department
Map<String, Long> employeeCount =
employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.counting()
));
System.out.println(employeeCount);Q34. Join employee names using a comma separator
String employeeNames = employees.stream()
.map(Employee::getName)
.collect(Collectors.joining(", "));
System.out.println(employeeNames);Q35. Find employees earning more than 75,000
List<Employee> highSalaryEmployees =
employees.stream()
.filter(e -> e.getSalary() > 75000)
.collect(Collectors.toList());Interview follow-up: How would you sort these employees by salary after filtering?
List<Employee> result = employees.stream()
.filter(e -> e.getSalary() > 75000)
.sorted(
Comparator.comparingDouble(
Employee::getSalary
).reversed()
)
.collect(Collectors.toList());Q36. Find the highest salary in each department
Map<String, Double> highestSalary =
employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.mapping(
Employee::getSalary,
Collectors.maxBy(
Double::compareTo
)
)
))
.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().orElse(0.0)
));This demonstrates combining groupingBy(), mapping() and maxBy().
Q37. Convert employee list into a Map using employee ID
Map<Integer, Employee> employeeMap =
employees.stream()
.collect(Collectors.toMap(
Employee::getId,
Function.identity()
));Important: If employee IDs are duplicated, toMap() throws an IllegalStateException unless you supply a merge function.
For example:
Map<Integer, Employee> employeeMap =
employees.stream()
.collect(Collectors.toMap(
Employee::getId,
Function.identity(),
(existing, replacement) -> existing
));Q38. Find the total salary expenditure of the company
double totalSalary = employees.stream()
.mapToDouble(Employee::getSalary)
.sum();
System.out.println(totalSalary);Q39. Find the employee with the longest name
Optional<Employee> employeeWithLongestName =
employees.stream()
.max(
Comparator.comparingInt(
e -> e.getName().length()
)
);Q40. Find employees whose salary is above their department's average
Map<String, Double> departmentAverage =
employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.averagingDouble(
Employee::getSalary
)
));
List<Employee> aboveAverageEmployees =
employees.stream()
.filter(e -> e.getSalary() >
departmentAverage.get(e.getDepartment()))
.collect(Collectors.toList());Why is this interesting?
This problem requires two stream operations:
Calculate the average salary for every department.
Compare each employee's salary against the corresponding department average.
This is a useful example of using streams for multi-step business logic.
Section 5: flatMap and Nested Collections
Q41. Flatten a list of lists into a single list
Problem: Convert nested collections into a single collection.
List<List<Integer>> nestedList = Arrays.asList(
Arrays.asList(1, 2, 3),
Arrays.asList(4, 5, 6),
Arrays.asList(7, 8, 9)
);
List<Integer> flattenedList = nestedList.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(flattenedList);Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]Interview concept:
map()transforms each element into one result.flatMap()transforms each element into a stream and flattens the resulting streams into one stream.
Q42. Find common elements between two lists
List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list2 = Arrays.asList(3, 4, 5, 6, 7);
List<Integer> commonElements = list1.stream()
.filter(list2::contains)
.distinct()
.collect(Collectors.toList());
System.out.println(commonElements);Output:
[3, 4, 5]Performance tip: For large lists, convert the second collection into a HashSet first to make membership checks typically constant-time.
Q43. Find elements present in the first list but not in the second
Set<Integer> secondSet = new HashSet<>(list2);
List<Integer> difference = list1.stream()
.filter(n -> !secondSet.contains(n))
.collect(Collectors.toList());
System.out.println(difference);Output:
[1, 2]Q44. Find all unique words from a list of sentences
List<String> sentences = Arrays.asList(
"Java is powerful",
"Java supports streams",
"Streams simplify Java programming"
);
List<String> uniqueWords = sentences.stream()
.flatMap(sentence ->
Arrays.stream(sentence.split("\\s+"))
)
.map(String::toLowerCase)
.distinct()
.collect(Collectors.toList());
System.out.println(uniqueWords);Note: This example uses whitespace tokenisation. Punctuation normalisation would be needed for more general text processing.
Section 6: String and Character Coding Problems
Q45. Find the first non-repeating character in a string
String input = "swiss";
Optional<Character> firstNonRepeating =
input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new,
Collectors.counting()
))
.entrySet()
.stream()
.filter(entry -> entry.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst();
System.out.println(firstNonRepeating.orElse(null));Output:
wWhy use LinkedHashMap?
It preserves insertion order, allowing us to identify the first character that occurs only once.
Q46. Find the first repeating character
String input = "programming";
Set<Character> seen = new HashSet<>();
Optional<Character> firstRepeating =
input.chars()
.mapToObj(c -> (char) c)
.filter(c -> !seen.add(c))
.findFirst();
System.out.println(firstRepeating.orElse(null));Output:
rInterview concept: This uses a stateful predicate. It works for a sequential stream, but should not be used with a parallel stream because the shared mutable set is not thread-safe.
Q47. Check whether two strings are anagrams
String first = "listen";
String second = "silent";
String sortedFirst = first.chars()
.sorted()
.collect(
StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append
)
.toString();
String sortedSecond = second.chars()
.sorted()
.collect(
StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append
)
.toString();
boolean isAnagram = sortedFirst.equals(sortedSecond);
System.out.println(isAnagram);Output:
trueThis version is case-sensitive and considers whitespace significant. Normalise the inputs first if the business requirement is case-insensitive comparison.
Section 7: Advanced Java Stream API Problems
Q48. Find all prime numbers within a range
List<Integer> primes = IntStream.rangeClosed(2, 50)
.filter(n ->
IntStream.rangeClosed(2, (int) Math.sqrt(n))
.allMatch(i -> n % i != 0)
)
.boxed()
.collect(Collectors.toList());
System.out.println(primes);Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]Explanation:
rangeClosed()generates numbers including the upper bound.allMatch()checks whether every divisor candidate satisfies the condition.boxed()converts primitive integers intoIntegerobjects.
Q49. Calculate the sum of digits of a number
int number = 12345;
int digitSum = String.valueOf(number)
.chars()
.map(Character::getNumericValue)
.sum();
System.out.println(digitSum);Output:
15Note: This concise example assumes a non-negative decimal integer. Handle negative values and input validation explicitly if required.
Q50. Generate the Fibonacci sequence using Stream API
List<Integer> fibonacci = Stream.iterate(
new int[]{0, 1},
pair -> new int[]{
pair[1],
pair[0] + pair[1]
}
)
.limit(10)
.map(pair -> pair[0])
.collect(Collectors.toList());
System.out.println(fibonacci);Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]Interview concept: Java 8's Stream.iterate() allows generating an infinite sequential stream. Always use a limiting operation when you need a finite result.
Section 8: Important Java Stream API Interview Concepts
Understanding coding problems is only half the preparation. Experienced developers should also understand the underlying behaviour of the Stream API.
1. Difference between map() and flatMap()
| map() | flatMap() |
|---|---|
| Transforms each element | Transforms and flattens |
| One output per input | Zero, one or many outputs per input |
| Can produce nested structures | Produces a flattened stream |
| Example: String to uppercase | Example: List of Lists to List |
2. Intermediate vs terminal operations
Intermediate operations:
filter()
map()
flatMap()
distinct()
sorted()
limit()
skip()
peek()
Terminal operations:
collect()
forEach()
count()
reduce()
min()
max()
findFirst()
findAny()
anyMatch()
allMatch()
noneMatch()
Intermediate operations are generally lazy. Processing begins when a terminal operation is invoked.
3. What is lazy evaluation?
Consider:
List<Integer> result = numbers.stream()
.filter(n -> {
System.out.println("Filtering: " + n);
return n > 5;
})
.map(n -> n * 2)
.collect(Collectors.toList());The stream pipeline does not process the elements when it is created. Processing starts when collect() is executed.
This allows the Stream API to optimise execution and avoid unnecessary intermediate collections.
4. Difference between findFirst() and findAny()
findFirst()returns the first element according to the stream's encounter order, when one exists.findAny()may return any element and is useful when the actual first element is not important, especially with parallel streams.
5. What is reduce()?
reduce() combines elements into a single result.
Example:
int total = numbers.stream()
.reduce(0, Integer::sum);
System.out.println(total);The identity value is 0, and the accumulator combines the values.
6. What are parallel streams?
Parallel streams divide work across multiple processing threads using the Java fork/join infrastructure.
List<Integer> result = numbers.parallelStream()
.filter(n -> n > 5)
.map(n -> n * 2)
.collect(Collectors.toList());Parallel streams are not automatically faster.
Consider:
Dataset size.
CPU-intensive versus I/O-intensive work.
Cost of splitting the source.
Combining partial results.
Thread safety.
Shared mutable state.
Common ForkJoinPool contention.
Use benchmarking rather than assuming parallel execution improves performance.
7. Can a stream be reused?
No. Once a terminal operation consumes a stream, it cannot be reused.
Incorrect:
Stream<Integer> stream = numbers.stream();
stream.forEach(System.out::println);
stream.count(); // IllegalStateExceptionCorrect:
long count = numbers.stream().count();
numbers.stream().forEach(System.out::println);Create a new stream whenever you need another pipeline.
Section 9: Common Mistakes in Java Stream API Interviews
Using
map()whenflatMap()is required.Forgetting that streams are lazy.
Reusing a stream after a terminal operation.
Using
get()on an empty Optional.Ignoring duplicate keys in
Collectors.toMap().Using mutable shared variables in parallel streams.
Assuming parallel streams are always faster.
Modifying a collection while it is being streamed.
Using
peek()as a replacement for proper processing.Ignoring the cost of sorting large datasets.
Senior developers should be able to explain not just how a solution works, but why it is appropriate for a particular production scenario.
Section 10: Frequently Asked Questions
1. Is Java Stream API available from Java 8?
Yes. Stream API was introduced in Java 8 through java.util.stream.
2. Are Java Streams and Collections the same?
No. Collections store data. Streams provide a pipeline for processing data from a source.
3. Can we modify a collection while using its stream?
You should not structurally modify the source collection during stream processing. This can cause unpredictable behaviour or exceptions.
4. What is the difference between Collection.stream() and Collection.parallelStream()?
stream() creates a sequential stream, while parallelStream() creates a potentially parallel stream.
5. What is the difference between collect() and reduce()?
collect() is designed for mutable reduction, such as building collections or grouped results. reduce() combines values into a result using an associative reduction operation.
6. What is Collectors.groupingBy()?
It groups elements based on a classification function and can apply downstream collectors such as counting(), averagingDouble() and mapping().
7. Does Stream API modify the original collection?
Ordinary stream operations do not modify the source collection. However, side effects inside lambdas can modify external state, which should generally be avoided.
8. When should we avoid Streams?
Traditional loops can be clearer for complex stateful algorithms, heavy debugging, intricate control flow or performance-sensitive situations where benchmarking shows streams are unsuitable.
Conclusion
Java Stream API is more than a convenient replacement for traditional loops. It provides a declarative way to express data-processing operations and is particularly useful when working with collections, employee records, transactions, reporting and business data.
For experienced Java developers, the most important areas to master are:
map()andflatMap()filter()anddistinct()Collectors.groupingBy()Collectors.partitioningBy()Collectors.toMap()Collectors.mapping()Collectors.reducing()Optionalreduce()Parallel stream behaviour
Practise these 50 problems, understand the underlying execution and be ready to discuss performance, edge cases and alternative implementations.