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