So, my goal here is to create a method where I pass in a list of CabinAvailability objects and add each of the booked properties to get a total. However, there is an error with the totalBooked variable and the suggestion in Intellij says to make the variable final, which doesn’t solve the issue. Any ideas? Thanks
Here is the method:
private int getTotalBooked(List<CabinAvailability> cabinAvailability) {
int totalBooked = 0;
cabinAvailability.forEach(cabin -> totalBooked = totalBooked + cabin.getBooked());
return totalBooked;
}
>Solution :
You cannot assign to a local variable from inside a lambda expression.
Either refactor your code to follow an imperative style (a simple for-loop) or use a stream-based solution like,
private int getTotalBooked(List<CabinAvailability> cabinAvailability) {
return cabinAvailability.stream()
.mapToInt(CabinAvailability::getBooked)
.sum();
}
