Top 50 Java Stream API Coding Questions Asked in Interviews
Most-asked problems solved using Stream API – Java 8+, Based on Java Stream API interview patterns. Java Stream API Interview Questions with Solutions & Complexity
Basic Stream Questions
- Filter even numbers from a list
- Filter odd numbers from a list
- Find numbers greater than a given value
- Count elements in a list
- Remove duplicate elements from a list
- Sort a list in ascending order
- Sort a list in descending order
- Convert list of strings to uppercase
- Convert list of strings to lowercase
- Find first element of a stream
Numeric & Aggregation Problems
- Find sum of all numbers
- Find average of numbers
- Find maximum number
- Find minimum number
- Find second highest number
- Find second lowest number
- Find top N highest numbers
- Find bottom N smallest numbers
- Multiply all numbers using reduce
- Find sum of squares of numbers
String-Based Stream Questions
- Find longest string in a list
- Find shortest string in a list
- Count strings starting with a specific character
- Join strings with a delimiter
- Remove null or empty strings
- Sort strings by length
- Find duplicate strings
- Find unique strings
- Find first non-repeating character in a string
- Count frequency of each character
Map & Grouping Questions
- Group employees by department
- Count employees in each department
- Find highest-paid employee per department
- Convert list to map (id → object)
- Partition numbers into even and odd
- Group numbers by odd/even
- Group strings by length
- Count frequency of elements in a list
- Find duplicate elements with count
- Sort map by values
Advanced / Real-World Stream Questions
- Flatten a list of lists using flatMap
- Find total salary of all employees
- Find employee with maximum salary
- Find employees whose salary is greater than average
- Find common elements between two lists
- Find difference between two lists
- Remove duplicates while preserving order
- Check if all numbers are positive
- Check if any number is negative
- Convert stream result into an immutable collection
Top 50 Java Stream API Coding Questions – Solutions with Complexity
Common Setup (Used by All Examples)
import java.util.*;
import java.util.stream.*;
List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 20, 10, 50);
List<String> names = Arrays.asList("Java", "Spring", "Boot", "Java", "API", "", null);
1️⃣ Filter even numbers
List<Integer> evens = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println("Even Numbers: " + evens);
🧠 Scans list and keeps divisible by 2
⏱ Time Complexity: O(n) – O(n) time complexity, or linear time, means that the running time of an algorithm grows linearly and in direct proportion to the size of the input data, denoted as n.
2️⃣ Filter odd numbers
List<Integer> odds = numbers.stream()
.filter(n -> n % 2 != 0)
.collect(Collectors.toList());
System.out.println("Odd Numbers: " + odds);
⏱ O(n)
3️⃣ Numbers greater than 25
List<Integer> greaterThan25 = numbers.stream()
.filter(n -> n > 25)
.collect(Collectors.toList());
System.out.println("Greater than 25: " + greaterThan25);
⏱ O(n)
4️⃣ Count elements
long count = numbers.stream().count();
System.out.println("Count: " + count);
⏱ O(1) (size is known) – or constant time complexity, means that the execution time or memory usage of an algorithm remains the same regardless of the size of the input data.
5️⃣ Remove duplicates
List<Integer> unique = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println("Unique Numbers: " + unique);
⏱ O(n) (uses HashSet internally) refers to a specific algorithm or operation whose space complexity is O(n), or whose worst-case time complexity is O(n), due to the internal use and mechanics of a hash set.
6️⃣ Sort ascending
List<Integer> sortedAsc = numbers.stream()
.sorted()
.collect(Collectors.toList());
System.out.println("Sorted Asc: " + sortedAsc);
⏱ O(n log n) – means the time complexity of an algorithm grows proportional to n × log n, where:
log n = logarithm of n (usually base 2 in computer science)
n = number of input elements
7️⃣ Sort descending
List<Integer> sortedDesc = numbers.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println("Sorted Desc: " + sortedDesc);
⏱ O(n log n)
8️⃣ Convert strings to uppercase
List<String> upperCase = names.stream()
.filter(Objects::nonNull)
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println("Uppercase: " + upperCase);
⏱ O(n)
9️⃣ Convert strings to lowercase
List<String> lowerCase = names.stream()
.filter(Objects::nonNull)
.map(String::toLowerCase)
.collect(Collectors.toList());
System.out.println("Lowercase: " + lowerCase);
⏱ O(n)
🔟 Find first element
Optional<Integer> first = numbers.stream().findFirst();
System.out.println("First Element: " + first.orElse(null));
⏱ O(1) (short-circuit operation)
1️⃣1️⃣ Sum of numbers
int sum = numbers.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum: " + sum);
⏱ O(n)
1️⃣2️⃣ Average of numbers
double average = numbers.stream()
.mapToInt(Integer::intValue)
.average()
.orElse(0);
System.out.println("Average: " + average);
⏱ O(n)
1️⃣3️⃣ Maximum number
int max = numbers.stream()
.max(Integer::compareTo)
.orElse(0);
System.out.println("Max: " + max);
⏱ O(n)
1️⃣4️⃣ Minimum number
int min = numbers.stream()
.min(Integer::compareTo)
.orElse(0);
System.out.println("Min: " + min);
⏱ O(n)
1️⃣5️⃣ Second highest number
Integer secondHighest = numbers.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst()
.orElse(null);
System.out.println("Second Highest: " + secondHighest);
⏱ O(n log n)
1️⃣6️⃣ Second lowest number
Integer secondLowest = numbers.stream()
.distinct()
.sorted()
.skip(1)
.findFirst()
.orElse(null);
System.out.println("Second Lowest: " + secondLowest);
⏱ O(n log n)
1️⃣7️⃣ Top 3 highest numbers
List<Integer> top3 = numbers.stream()
.sorted(Comparator.reverseOrder())
.limit(3)
.collect(Collectors.toList());
System.out.println("Top 3: " + top3);
⏱ O(n log n)
1️⃣8️⃣ Bottom 3 smallest numbers
List<Integer> bottom3 = numbers.stream()
.sorted()
.limit(3)
.collect(Collectors.toList());
System.out.println("Bottom 3: " + bottom3);
⏱ O(n log n)
1️⃣9️⃣ Multiply all numbers
int product = numbers.stream()
.reduce(1, (a, b) -> a * b);
System.out.println("Product: " + product);
It will give result in -ve number like -11122333
> so use -1 / minus as initial value.
int product = numbers.stream().reduce(-1, (a, b) -> a * b);
OR
int product = -numbers.stream().reduce(1, (a, b) -> a * b);
⏱ O(n)
2️⃣0️⃣ Sum of squares
int sumOfSquares = numbers.stream()
.map(n -> n * n)
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum of Squares: " + sumOfSquares);
⏱ O(n)
Java Stream API Interview Questions (21–50)
✅ Employee Model (Required for Q21–Q40)
class Employee {
private int id;
private String name;
private String dept;
private double salary;
public Employee(int id, String name, String dept, double salary) {
this.id = id;
this.name = name;
this.dept = dept;
this.salary = salary;
}
public int getId() { return id; }
public String getName() { return name; }
public String getDept() { return dept; }
public double getSalary() { return salary; }
@Override
public String toString() {
return name + " (" + dept + ", " + salary + ")";
}
}
✅ Sample Employee Data
List<Employee> employees = Arrays.asList(
new Employee(1, "Amit", "IT", 60000),
new Employee(2, "Rahul", "HR", 50000),
new Employee(3, "Sneha", "IT", 80000),
new Employee(4, "Priya", "Finance", 70000),
new Employee(5, "Kunal", "HR", 55000)
);
🔹 21. Group employees by department
Map<String, List<Employee>> byDept = employees.stream().collect(Collectors.groupingBy(Employee::getDept));
System.out.println("Employees by Dept: " + byDept);
⏱ O(n)
🔹 22. Count employees per department
Map<String, Long> deptCount =
employees.stream()
.collect(Collectors.groupingBy(
Employee::getDept, Collectors.counting()));
System.out.println("Dept Count: " + deptCount);
⏱ O(n)
🔹 23. Highest paid employee per department
// case1: Get employeee based in dept
Map<String, Optional<Employee>> highestPaid =
employees.stream()
.collect(Collectors.groupingBy(
Employee::getDept,
Collectors.maxBy(Comparator.comparing(Employee::getSalary))));
System.out.println("Highest Paid per Dept: " + highestPaid);
//case 2: Get Employee Name instead of the employee
Map<String, String> highestPaid =
employees.stream()
.collect(Collectors.groupingBy(
Employee::getDept,
Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparing(Employee::getSalary)),
opt -> opt.map(Employee::getName).orElse("N/A")
)));
System.out.println("Highest Paid per Dept: " + highestPaid);
⏱ O(n)
🔹 24. Convert employee list to map (id → employee)
Map<Integer, Employee> empMap =
employees.stream()
.collect(Collectors.toMap(Employee::getId, e -> e));
System.out.println("Employee Map: " + empMap);
⏱ O(n)
🔹 25. Total salary of all employees
double totalSalary =
employees.stream()
.mapToDouble(Employee::getSalary) //or .mapToDouble(e -> e.getSalary())
.sum(); // orElse not required
System.out.println("Total Salary: " + totalSalary);
⏱ O(n)
🔹 26. Average salary
double avgSalary =
employees.stream()
.mapToDouble(Employee::getSalary)
.average()
.orElse(0); //avergage work with orElse
System.out.println("Average Salary: " + avgSalary);
⏱ O(n)
🔹 27. Employee with max salary
Employee maxSalaryEmp =
employees.stream()
.max(Comparator.comparing(Employee::getSalary))
.orElse(null);
System.out.println("Max Salary Employee: " + maxSalaryEmp);
// Get employee name instead
String maxSalaryEmpName= employees.stream()
.max(Comparator.comparing(Employee::getSalary))
.map(Employee::getName)
.orElse(null);
⏱ O(n)
🔹 28. Employees earning more than average salary
//get average salary first,already given code above
double avgSalary = employees.stream()
.mapToDouble(Employee::getSalary)
.average()
.orElse(0.0);
// print employee list
List<Employee> aboveAvg =
employees.stream()
.filter(e -> e.getSalary() > avgSalary)
.collect(Collectors.toList());
System.out.println("Above Avg Salary: " + aboveAvg); //Above Avg Salary: [Employee@5451c3a8, Employee@2626b418]
//print name of employee
List<String> aboveAvgNames =
employees.stream()
.filter(e -> e.getSalary() > avgSalary)
.map(Employee::getName)
.collect(Collectors.toList());
System.out.println("Above Avg Salary Employees: " + aboveAvgNames); ////Above Avg Salary Employees: [Sneha, Priya]
⏱ O(n)
🔹 29. Partition employees based on salary > 60000
Map<Boolean, List<Employee>> salaryPartition =
employees.stream()
.collect(Collectors.partitioningBy(e -> e.getSalary() > 60000));
System.out.println("Salary Partition: " + salaryPartition);
// output : parttitioningBy: {false=[Employee@66d3c617, Employee@63947c6b, Employee@2b193f2d, Employee@355da254, Employee@4dc63996], true=[]}
// for > 700000 example output :" parttitioningBy: {false=[Employee@66d3c617, Employee@63947c6b, Employee@2b193f2d, Employee@355da254], true=[Employee@4dc63996]}
⏱ O(n)
🔹 30. Sort employees by salary
List<Employee> sortedBySalary =
employees.stream()
.sorted(Comparator.comparing(Employee::getSalary))
.collect(Collectors.toList());
System.out.println("Sorted by Salary: " + sortedBySalary); //Sorted by Salary: [Employee@4dc63996, Employee@d716361, Employee@6ff3c5b5, Employee@3764951d, Employee@4b1210ee]
// by salary and show salary
List<Double> sortedEmp = employees.stream()
.sorted(Comparator.comparing(e->e.getSalary()))
.map(e -> e.getSalary())
.collect(Collectors.toList()); // sortedEmp: [50000.0, 55000.0, 60000.0, 70000.0, 80000.0]
⏱ O(n log n)
🔹 31. Names of all employees
List<String> empNames =
employees.stream()
.map(Employee::getName)
.collect(Collectors.toList());
System.out.println("Employee Names: " + empNames);
⏱ O(n)
🔹 32. Count employees with salary > 60000
long highEarners =
employees.stream()
.filter(e -> e.getSalary() > 60000)
.count();
System.out.println("High Earners Count: " + highEarners); //2
⏱ O(n)
🔹 33. Check if any employee from HR
boolean hasHR =
employees.stream()
.anyMatch(e -> "HR".equals(e.getDept()));
System.out.println("Has HR Dept? " + hasHR); //true
⏱ O(n)
🔹 34. Check if all employees earn above 40k
boolean allAbove40k =
employees.stream()
.allMatch(e -> e.getSalary() > 40000);
System.out.println("All earn > 40k? " + allAbove40k); //true
⏱ O(n)
🔹 35. Find employee by name
Employee emp =
employees.stream()
.filter(e -> "Sneha".equals(e.getName()))
.findFirst()
.orElse(null);
System.out.println("Employee Found: " + emp); //Employee Found [Amit, Rahul, Sneha, Priya, Kunal]
⏱ O(n)
🔹 36. Sort employees by name
List<Employee> sortedByName =
employees.stream()
.sorted(Comparator.comparing(Employee::getName))
.collect(Collectors.toList());
System.out.println("Sorted by Name: " + sortedByName);
//for list of name
List<String> sortedEmp = employees.stream()
.sorted(Comparator.comparing(Employee::getName))
.map(e -> e.getName())
.collect(Collectors.toList());
System.out.println("sortedEmp: " + sortedEmp); //sortedEmp: [Amit, Kunal, Priya, Rahul, Sneha]
⏱ O(n log n)
🔹 37. Group employees by salary range
Map<String, List<Employee>> salaryRange =
employees.stream()
.collect(Collectors.groupingBy(e ->
e.getSalary() > 60000 ? "HIGH" : "LOW"));
System.out.println("Salary Range: " + salaryRange);
output// Salary Range: {HIGH=[Employee@66d3c617, Employee@63947c6b], LOW=[Employee@2b193f2d, Employee@355da254, Employee@4dc63996]}
⏱ O(n)
🔹 38. Find department names (unique)
Set<String> departments =
employees.stream()
.map(Employee::getDept)
.collect(Collectors.toSet());
System.out.println("Departments: " + departments); //Salary Range: [IT, HR, Finance]
//or using list
List<String> salaryRange =
employees.stream().map(e -> e.getDept())
.distinct() //manual unique
.collect(Collectors.toList());
⏱ O(n)
🔹 39. Employee count
System.out.println("Employee Count: " + employees.stream().count());
⏱ O(1)
🔹 40. Convert employees to immutable list
List<Employee> immutableList =
employees.stream().toList();
System.out.println("Immutable Employee List: " + immutableList);
⏱ O(n)
✔ Immutable only in Java 16+
Stream.toList()(added in Java 16) returns an unmodifiable list- You cannot add, remove, or replace elements
- immutableList.add(emp); // ❌ UnsupportedOperationException
Stream.toList()returns an unmodifiable list, but objects inside the list are still mutable.
Java 8–15 ⚠️ That returns a mutable ArrayList
🔹 41–50 (Generic Stream Checks)
// 41. Any employee salary < 50k
System.out.println(
employees.stream().anyMatch(e -> e.getSalary() < 50000)
);
// 42. None employee salary < 30k
System.out.println(
employees.stream().noneMatch(e -> e.getSalary() < 30000)
);
// 43. Find first IT employee
System.out.println(
employees.stream().filter(e -> "IT".equals(e.getDept())).findFirst().orElse(null)
);
// 44. Limit first 3 employees
System.out.println(
employees.stream().limit(3).collect(Collectors.toList())
);
// 45. Skip first 2 employees
System.out.println(
employees.stream().skip(2).collect(Collectors.toList())
);
// 46. Debug stream using peek
employees.stream()
.peek(e -> System.out.println("Processing: " + e))
.collect(Collectors.toList());
Output like::
Processing: Employee@266474c2
Processing: Employee@2b193f2d
Processing: Employee@355da254
Processing: Employee@4dc63996
Processing: Employee@d716361
// 47. Convert salaries to list
System.out.println(
employees.stream().map(Employee::getSalary).collect(Collectors.toList())
);
// 48. Sum salary using reduce
System.out.println(
employees.stream().map(Employee::getSalary).reduce(0.0, Double::sum)
);
OR
System.out.println(
employees.stream().map(Employee::getSalary).reduce(0.0, (a,b) -> a + b)
);
// 49. Parallel stream example
System.out.println(
employees.parallelStream().map(Employee::getName).collect(Collectors.toList())
);
// 50. Stream reuse (NOT allowed)
// Stream<Employee> s = employees.stream();
// s.count();
// s.forEach(System.out::println); ❌ IllegalStateException
Java Stream API – Complete Guide with All Methods (Interview & Real-World Examples)
