🔹 Introduction
This is a very common Java Streams interview question, especially for backend roles.
👉 It tests your understanding of:
-
groupingBy() -
maxBy() -
Comparator
🔹 Problem Statement
Given a list of employees, find the highest salary in each department.
🔹 Example
Input:
IT → 50000, 70000
HR → 40000, 60000
Output:
IT → 70000
HR → 60000
🔹 Approach (Using Java Streams)
💡 Explanation
- Group employees by department
- Find max salary in each group
-
Use
Collectors.maxBy()
🔹 Employee Class
class Employee {
String name;
String department;
double salary;
public Employee(String name, String department, double salary) {
this.name = name;
this.department = department;
this.salary = salary;
}
public String getDepartment() { return department; }
public double getSalary() { return salary; }
}
🔹 Java Code (Streams Solution)
import java.util.*;
import java.util.stream.*;
import java.util.Comparator;
public class HighestSalary {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("A", "IT", 50000),
new Employee("B", "IT", 70000),
new Employee("C", "HR", 40000),
new Employee("D", "HR", 60000)
);
Map<String, Optional<Employee>> result =
employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.maxBy(Comparator.comparing(Employee::getSalary))
));
result.forEach((dept, emp) ->
System.out.println(dept + " -> " + emp.get().getSalary()));
}
}
🔹 Output
IT -> 70000
HR -> 60000
🔍 Internal Working (Important for Interviews)
-
groupingBy()→ groups by department -
maxBy()→ finds highest salary -
Comparator.comparing()→ compares salary
🔹 Time Complexity
- O(n)
🔹 Key Takeaways
✔ groupingBy() is very important
✔ maxBy() helps find max values
✔ Real-world interview question
🔹 Conclusion
This is a must-know Java Streams problem for backend developers.
Mastering this will help you crack mid-level interviews.
Comments
Post a Comment