Find Employees with the same salary using Java 8 Streams

By | March 23, 2023

Assuming you have a collection of Employee objects with a “salary” attribute, you can use Java 8 Streams to group employees by their salaries and then return a map where the keys are salaries and the values are lists of employees with the same salary. Here’s an example code snippet:

import java.util.*;
import java.util.stream.Collectors;

public class Employee {
private String name;
private double salary;

public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}

public String getName() {
return name;
}

public double getSalary() {
return salary;
}

public String toString() {
return name + ” – ” + salary;
}

public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee(“John”, 1000),
new Employee(“Jane”, 1500),
new Employee(“Bob”, 1000),
new Employee(“Mary”, 2000),
new Employee(“Tom”, 1500)
);

Map<Double, List<Employee>> employeesBySalary = employees.stream()
.collect(Collectors.groupingBy(Employee::getSalary));

employeesBySalary.forEach((salary, employeeList) -> {
System.out.println(“Employees with salary ” + salary);
employeeList.forEach(System.out::println);
System.out.println();
});
}
}

OUTPUT:

Employees with salary 1500.0
Jane – 1500.0
Tom – 1500.0

Employees with salary 2000.0
Mary – 2000.0

Employees with salary 1000.0
John – 1000.0
Bob – 1000.0

In this example, we create a list of Employee objects and then use the stream() method to create a stream of employees. We then use the Collectors.groupingBy() method to group the employees by their salary, which returns a map with the salary as the key and a list of employees with that salary as the value. We then iterate over the map using the forEach() method and print out the employees for each salary

Leave a Reply

Your email address will not be published. Required fields are marked *