1. 程式人生 > 其它 >Stream()——報錯使用final變數解決辦法

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());