Consider, I have the following class.
public class Employee {
private Integer id;
private Integer parentId;
private int value;
}
Now I have the following records.
Employee employee1 = new Employee(1, null, 4);
Employee employee2 = new Employee(2, 1, 4);
Employee employee3 = new Employee(3, null, 8);
Employee employee4 = new Employee(4, 1, 3);
Employee employee5 = new Employee(5, 2, 11);
So the parentId is the id of an employee who is the boss of another employee.
The question is to find out the sum of the value of an employee and it's parent if it has any, or return the value as it is. So in this case, the result should be.
| id | value |
|---|---|
| 1 | 4 |
| 2 | 8 |
| 3 | 8 |
| 4 | 7 |
| 5 | 15 |
How to achieve this using java 8 streams? I have tried the following;
Optional<Integer> first = employees.stream().map(a -> {
int sum = 0;
employees.stream().map(b -> {
if (Objects.equals(a.id, b.parentId)) {
sum = sum + a.value + b.value;
}else{
sum = sum + a.value;
}
return sum;
});
return sum;
}
).findFirst();
But I am getting error with the sum variable that it should be final or effectively final.