-4

I have a SeniorEmployee class which has some attributes and under the same I have JuniorEmployee list. Now my criteria is to iterate in SeniorEmployee though streams and based on some criteria and then for the SeniorEmployee matching with the filter criteria we need to iterate in the juniorEmployee list and calculate their total salary. So, how can I do it in a single lambda expression though stream? Please help.

SeniorEmployee id filter criteria is if EmpCode is 10;

    SeniorEmployee{
    empCode;
    List<JuniorEmployee> junEmpList
    }

    JuniorEmployee{
     Emp Id;
    Salary;
}
Amit Bera
  • 7,075
  • 1
  • 19
  • 42
Souvik
  • 1,219
  • 3
  • 16
  • 38

1 Answers1

0
seniors.stream().filter(x -> YOUR_SENIOR_CONDITION).mapToInt(x -> x.junEmpList.stream().mapToInt(y -> y.salary).sum()).sum()

or per your suggestion, try this:

seniors.stream().filter(x -> YOUR_SENIOR_CONDITION).flatMap(z -> z.junEmpList.stream()).mapToInt(o -> o.salary).sum();
Lukas Novicky
  • 921
  • 1
  • 19
  • 44
  • Can we do it with reduce? I found a solution where after first filter I am using flatMap to get the second List and then iside flatMap create another stream of JuniorEmp? – Souvik Apr 11 '19 at 09:14
  • check my edited answer. If it works for you, please mark answer as correct. – Lukas Novicky Apr 11 '19 at 09:41