Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function to add properties from list of object not working with forEach()

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;
  }

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading