I am trying to find the Salary of the Newest Employee for every Department. Using java 8 in a single step

526 Views Asked by At

Aim is to find the Salary of the newest Employee in the Department considering employee ID will increase. I have written a 2 step code and I am trying to find a solution that can do this in a single step using java8.

My Process is:

  1. get a Map of "Department" : "Newest Employee" based on Largest EmployeeId in that Department
  2. Use the Previous Map to create "Department" : "Salary of the Newest Employee" (This is the output)

Will it be possible to do it in a single step?

    public static void main(String[] args) {
    List<Employee> employees = new ArrayList<>();
    Employee e1 = new Employee(1, 1000, "a1", "A");
    Employee e2 = new Employee(2, 1010, "b1", "A");
    Employee e3 = new Employee(3, 1000, "a1", "B");
    Employee e4 = new Employee(4, 500, "b2", "B");
    Employee e5 = new Employee(5, 2000, "a1", "C");
    Employee e6 = new Employee(6, 5000, "b2", "C");
    employees.add(e1);
    employees.add(e2);
    employees.add(e3);
    employees.add(e4);
    employees.add(e5);
    employees.add(e6);
    //This Map will contain Department and The newest Employee in that Department.
    Map<String, Employee> retVal = employees.stream()
            .collect(groupingBy(
                    e -> e.getDepartment(),
                    collectingAndThen(maxBy(comparingInt(e -> e.getEmployeeId())), Optional::get)
            ));
    //This Map will use the previous map to construct a combination of "Department" : "Salary of the newest Member"
    Map<String, Integer> map = new HashMap<>();
    retVal.entrySet().forEach(stringEmployeeEntry -> {
        map.put(stringEmployeeEntry.getKey(), stringEmployeeEntry.getValue().getSalary());
    });
}

Output

{
  "a1" : 2000,
  "b1" : 1010,
  "b2" : 5000, 
}
1

There are 1 best solutions below

2
On

You can directly map the salary in collectingAndThen from Employee object

Map<String, Integer> retVal = employees.stream()
            .collect(Collectors.groupingBy(
                    e -> e.getDepartment(),
                    Collectors.collectingAndThen(
                         Collectors.maxBy(Comparator.comparingInt(e -> e.getEmployeeId())),
                         e -> e.get().getSalary())
            ));