Java Streams are a powerful feature introduced in Java 8 that enable functional-style operations on collections. Recently, I was asked a few Java Streams-related questions in an interview, and I would like to share my solutions along with explanations and better alternatives where applicable.
Interview Questions and Solutions
1. Get Employees Whose Salary is Greater Than 6000 and Name Starts With 'S'
Question:
Given a list of employees, filter out employees who earn more than 6000 and whose names start with the letter 'S'.
Solution:
List<Employee> empStartsWithS = employees.stream()
.filter(e -> e.getSalary() > 6000.0 && e.getName().toLowerCase().startsWith("s"))
.collect(Collectors.toList());
System.out.println(empStartsWithS);
Explanation:
filter()is used to apply the condition:salary > 6000andname starts with 's'.collect(Collectors.toList())collects the filtered elements into a new list.
Better Solution?
The current solution is optimal, but if case-sensitivity is not a concern, you can directly use startsWith("S") instead of toLowerCase().
2. Give a 40% Salary Hike to Each Employee and Print
Question:
Increase the salary of all employees by 40% and print the updated list.
Solution:
List<Employee> hiked = employees.stream()
.map(e -> new Employee(e.getId(), e.getName(), e.getSalary() * 1.4))
.collect(Collectors.toList());
System.out.println(hiked);
Explanation:
map()is used to transform each employee object.- A new Employee object is created with an updated salary.
collect(Collectors.toList())gathers the transformed employees into a list.
Why Create a New Employee Object?
If we modify the existing object inside map(), the original list (employees) will also be affected because Java passes object references. Creating a new object ensures immutability and prevents unintended modifications.
Wrong approach (Modifies existing list):
employees.stream()
.peek(e -> e.setSalary(e.getSalary() * 1.4))
.collect(Collectors.toList());
This approach changes employees directly, which might not be desirable.
3. Find the Employee with the Maximum Salary
Question:
Find the employee with the highest salary in the given list.
Solution:
Double maxSalariedEmp = employees.stream()
.max(Comparator.comparingDouble(Employee::getSalary))
.get()
.getSalary();
System.out.println(maxSalariedEmp);
Explanation:
max(Comparator.comparingDouble(Employee::getSalary))finds the employee with the highest salary..get()retrieves theOptional<Employee>result (ensure the list is non-empty)..getSalary()fetches the actual salary value.
Better Solution?
If you need the full employee details instead of just the salary, modify it like this:
Optional<Employee> maxEmployee = employees.stream()
.max(Comparator.comparingDouble(Employee::getSalary));
maxEmployee.ifPresent(System.out::println);
This prevents a NoSuchElementException if the list is empty.
Conclusion
These were some common interview questions based on Java Streams. Mastering these concepts can help in real-world applications where we need efficient data processing.
Key Takeaways:
- Use
filter()for selecting specific elements from a stream. - Use
map()to transform objects and maintain immutability. - Use
max()with a comparator to find the highest value. - Prefer creating new objects in transformations to avoid modifying the original list.
Comments
Post a Comment