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)
