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;

    }

}




public class StreamExample {
    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("Alice", "IT", 60000),
            new Employee("Bob", "HR", 45000),
            new Employee("Charlie", "Finance", 70000),
            new Employee("David", "IT", 55000),
            new Employee("Eve", "Finance", 40000)
        );

        // 1️⃣ Filter employees earning more than $50,000
        List<Employee> highEarners = employees.stream()
            .filter(e -> e.getSalary() > 50000)
            .collect(Collectors.toList());

        System.out.println("High Earners:");
        highEarners.forEach(System.out::println);

        // 2️⃣ Convert names to uppercase
        List<String> upperCaseNames = employees.stream()
            .map(e -> e.getName().toUpperCase())
            .collect(Collectors.toList());

        System.out.println("\nUppercase Names: " + upperCaseNames);

        // 3️⃣ Sort employees by salary (descending)
        List<Employee> sortedBySalary = employees.stream()
            .sorted((e1, e2) -> Double.compare(e2.getSalary(), e1.getSalary()))
            .collect(Collectors.toList());

        System.out.println("\nSorted by Salary:");
        sortedBySalary.forEach(System.out::println);

        // 4️⃣ Group employees by department
        Map<String, List<Employee>> groupedByDept = employees.stream()
            .collect(Collectors.groupingBy(Employee::getDepartment));

        System.out.println("\nEmployees Grouped by Department:");
        groupedByDept.forEach((dept, empList) -> {
            System.out.println(dept + ": " + empList);
        });

        // 5️⃣ Find the highest-paid employee
        Optional<Employee> highestPaid = employees.stream()
            .max(Comparator.comparingDouble(Employee::getSalary));

        System.out.println("\nHighest Paid Employee: " + highestPaid.orElse(null));

        // 6️⃣ Use Parallel Stream for Performance Boost
        double totalSalary = employees.parallelStream()
            .mapToDouble(Employee::getSalary)
            .sum();

        System.out.println("\nTotal Salary (Parallel Stream): $" + totalSalary);
    }
}


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