foreach循环中不能使用字符串拼接

2023年7月26日13:08:49

问题:

    @Test
    public void forEachTest(){

        String str = "中国你好!";

        List<String> list = Arrays.asList("a","b","c","d");
        
        list.forEach(item->{
        	//编辑错误:Variable used in lambda expression should be final or effectively final
            str += item;
        });

        //可以使用增强for
//        for (String item : list) {
//            str += item;
//        }

        System.out.println("结果:" + str);

    }

  该编译不通过的根本原因:Lambda表达式中的局部变量要使用final的问题。
  因为String类型属于引用数据类型,String字符串有不可变的特性,String在进行字符串拼接时,每次都会指向不同的地址值,因此str变量不能被看作是一个final类型,也就不符合Lambda表达式的使用要求。

解决:
使用StringBuffer或StringBuilder:

    @Test
    public void forEachTest(){

        //String str = "中国你好!";

        List<String> list = Arrays.asList("a","b","c","d");

        StringBuffer stringbuffer = new StringBuffer("中国你好!");
        list.forEach(item->{
            stringbuffer .append(item);
        });

        //可以使用增强for
//        for (String item : list) {
//            str += item;
//        }

        System.out.println("结果:" + sb);

    }

原理:
  StringBuffer是一个引用数据类型,在进行append()时,只是修改了内容,并没有改变地址值,这个stringbuffer变量就在编译时看成了final类型的变量,因此可以使用。

Lambda表达式中的局部变量要使用final的问题:https://blog.csdn.net/weixin_42921327/article/details/115657993

  • 作者:lhj_coder
  • 原文链接:https://blog.csdn.net/weixin_42921327/article/details/115672799
    更新时间:2023年7月26日13:08:49 ,共 926 字。