Stream()——报错使用final变量解决办法


问题:

  在使用Stream()流进行操作变量的时候,会不时碰到:variable used in lambda expression should be final or effectively final,这是因为在Java 8 之前,匿名类中如果要访问局部变量的话,那个局部变量必须显式的声明为final。

解决办法:

  (小白一个,勿喷)声明一个final变量进行重新赋值再进行流操作。

  String changeIdList = jsonObject.getString("changeIdList");
  // 局部变量
  List<Student> changeStudents = null;
  if (!changeIdList.equals("[]")){
    List<Long> longs = JSONObject.parseArray(changeIdList, Long.class);
    Student student = new Student();
    student.setDeptIds(longs);
    changeStudents = StudentService.selectStudentList(student);
  }
  // 重新赋值
  final List<Student> changeStudentList = changeStudents;
  List<Student> collect3 = changeStudentList == null ? collect2 : collect2.stream().filter(o ->
    !(changeStudentList.stream().map(Student::getSid).collect(Collectors.toList()).contains(o.getSid()))
  ).collect(Collectors.toList());

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM