Advanced Example with Java Stream API
🚀Let's go beyond the basics and explore advanced Stream API operations in Java, including grouping, partitioning, and parallel processing.
1️⃣ Imagine you have a list of employees, and you want to:
✅ Filter employees earning more than $50,000
✅ Convert employee names to uppercase
✅ Sort employees by salary
✅ Group employees by department
✅ Find the highest-paid employee
✅ Use parallel stream for better performance
📌 Employee Class
import java.util.*;
import java.util.stream.Collectors;
class Employee {
private String name;
private String department;
private double salary;
public Employee(String name, String department, double salary) {
this.name = name;
this.department = department;
this.salary = salary;
}
public String getName() { return name; }
public String getDepartment() { return department; }
public double getSalary() { return salary; }
@Override
public String toString() {
return name + " - " + department + " - $" + salary;
}
}
3️⃣ Explanation of Stream Operations
✅ Filtering (filter) → Keeps only employees earning more than $50,000
✅ Mapping (map) → Converts names to uppercase
✅ Sorting (sorted) → Sorts employees by salary in descending order
✅ Grouping (groupingBy) → Groups employees by department
✅ Finding Max (max) → Finds the highest-paid employee
✅ Parallel Processing (parallelStream) → Calculates total salary efficiently
4️⃣ Sample Output
High Earners:
Alice - IT - $60000.0
Charlie - Finance - $70000.0
David - IT - $55000.0
Uppercase Names: [ALICE, BOB, CHARLIE, DAVID, EVE]
Sorted by Salary:
Charlie - Finance - $70000.0
Alice - IT - $60000.0
David - IT - $55000.0
Bob - HR - $45000.0
Eve - Finance - $40000.0
Employees Grouped by Department:
IT: [Alice - IT - $60000.0, David - IT - $55000.0]
HR: [Bob - HR - $45000.0]
Finance: [Charlie - Finance - $70000.0, Eve - Finance - $40000.0]
Highest Paid Employee: Charlie - Finance - $70000.0
Total Salary (Parallel Stream): $270000.0
5️⃣ Summary
✔ Streams make processing collections easy & efficient
✔ Functional programming approach (filter, map, sort, reduce, group)
✔ Parallel streams help boost performance
Comments
Post a Comment