1

I want to iterate an array with some objects that contains a quantity and get the totalQuantity, but using the new API of Java 8 instead of the tipical for each loop.

This is the way I'm doing so far:

int totalQuantityOrdered=0;
    totalQuantityOrdered=CollectionUtils.isNotEmpty(details)?details.stream().forEach(detail->totalQuantityOrdered+=detail.getOrderHeader().getQuantity()):totalQuantityOrdered;

However I'm getting a compilation error telling me that in order to use a lambda expression the variable totalQuantityOrdered has to be final. Then I think when a variable is final means that its value cannot be modified, so in that case how do I achieve what I'm trying to do?

Thnk you in advance for your time.

Eran
  • 387,369
  • 54
  • 702
  • 768
fgonzalez
  • 3,787
  • 7
  • 45
  • 79
  • Related: http://stackoverflow.com/q/28961578/1639625 – tobias_k Mar 12 '15 at 13:49
  • This happens because in Lambda Expressions we cannot assign any value to some local variable declared outside it. So any variable used in a lambda is treated as final. – agamesh Mar 12 '15 at 13:49

1 Answers1

5

There's a much cleaner way to do this :

int totalQuantityOrdered = 
    details.stream()
           .mapToInt(detail -> detail.getOrderHeader().getQuantity())
           .sum();

This is assuming that getOrderHeader().getQuantity() returns an int.

Eran
  • 387,369
  • 54
  • 702
  • 768