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

前端 未结 4 1507
予麋鹿
予麋鹿 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条回答
  •  旧时难觅i
    2020-12-01 11:08

    1. No you can't do it. (Although you should have tried it yourself)
    2. Because variables used within anonymous inner classes and lambda expression have to be effectively final.
    3. you can achieve the same more concisely using filter and map.

      Optional d = list.stream()
                               .filter(c -> c.equals("d"))
                               .findFirst()
                               .map(c -> "match the value");
      

提交回复
热议问题