問題:
在使用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());
