In java8, how to set the global value in the lambdas foreach block?

前端 未结 4 1504
予麋鹿
予麋鹿 2020-12-01 10:49
    public void test(){
       String x;
       List list=Arrays.asList(\"a\",\"b\",\"c\",\"d\");

       list.forEach(n->{
          if(n.equals(\"         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 10:56

    As it's already explained, you cannot modify the local variable of the outer method from the lambda body (as well as from the anonymous class body). My advice is don't try to use lambdas when they are completely unnecessary. Your problem can be solved like this:

    public void test(){
       String x;
       List list = Arrays.asList("a","b","c","d");
       if(list.contains("d"))
           x = "match the value";
    }
    

    In general lambdas are friends with functional programming where you rarely have mutable variables (every variable is assigned only once). If you use lambdas, but continue thinking in imperative style you will always have such problems.

提交回复
热议问题