简体   繁体   中英

Referencing a local variable while iterate a HashMap -> local variables referenced from a lambda expression must be final or effectively final error

today i wanted to work on some projects i wanted to finish where i get an exception that i can not reference to a local variable from a lambda expression. I have a method where i give two values and th method checks if the value-pair is already in the HashMap

public void METHOD_NAME(Value value1, Value value2) {
    boolean founded = false;
  //values is the name of the HashMap
    this.values.forEach((value1Map, value2Map) -> {
            if(value1Map == value1&&value2Map == value2){
                this.doSomeStuff();
                founded = true;
            }

    });

}

and when its finished i want to read out the boolean needing to know if he doesent found it founded = false; how can i set founded in this lambda or are there any other ways to do this ?

You can use the atomic variants of primitives in lambdas. Replace

boolean founded = true

by this

final AtomicBoolean found = new AtomicBoolean(false);

and set it in within your lambda like this

found.set(true);

By the way, it is absolutely ok NOT to replace every iteration by a lambda. The for-loop still works and has its advantages over lambdas in some cases.

I've changed founded to found as Tom indicated in the comments of your question. Moreover, you should verify if you want to make the comparison with == instead of equals

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