简体   繁体   中英

Local variables referenced from a lambda expression must be final

I´m trying to create a getValue() function from a pojo that use summatory of details class values in this sense:

@Transient
public BigDecimal getValue() {
   BigDecimal sum = new BigDecimal(0);

   details.stream().forEach((detail) -> {
      sum = sum.add(detail.getValue());
   });

   return sum;
}

but I don't know why this the line sum = sum.add(detail.getValue()); provoke this error:

local variables referenced from a lambda expression must be final or effectively final

Can you say me what's I'am doing wrong. Thanks.

You cannot modify variables from inside a lambda. That's just not a thing you're allowed to do.

What you can do here is write this method as

return details.stream()
    .map(Detail::getValue)
    .reduce(BigDecimal.ZERO, BigDecimal::add);

Ok, just do not use the lambda expression in the foreach loop

@Transient
public BigDecimal getValue() {
   BigDecimal sum = new BigDecimal(0);

   for (Detail detail : details) {
      sum = sum.add(detail.getValue());
   }

   return sum;
}

this is my way to avoid final p in the loop and it worked.

public void getSolutionInfo(){      
ArrayList<Node> graph = Main.graph; 

    for(int p=1;p<=Pmax;p++) {          
        final int p2=p;
        System.out.printf("number of node with priority p = %d is %d ",p, graph.stream().filter(node->node.getPriority()==p2).count()); 
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM