List<Integer> list = Arrays.asList(1,2,3,4,5);
boolean flag = false;
List<Integer> newList = list.stream()
//many other filters, flatmaps, etc...
.filter(i -> {
if(condition(i)){
flag = true;
}
return condition(i);
})
//many other filters, flatmaps, etc...
.collect(Collectors.toList());
//do some work with the new list and the flag
然而,这违反了语言限制“lambda表达式中使用的变量应该是final或有效的final”。我能想到几种解决方案,但不确定哪种最好。我首先想到的解决方案是将与
condition
匹配的元素添加到列表中,并检查List::isEmpty
。也可以将flag
包装在AtomicReference
中。请注意,我的问题类似于这个问题,但我尝试在最后提取布尔值而不是设置变量。
flag
包装在AtomicReference
中。或者是AtomicBoolean
? - shmoselnewList.isEmpty()
,因为之前和之后应用了许多其他流操作。我必须为该条件创建一个新列表。这是我提到的可能解决方案之一。 - mitchfilter()
中产生副作用。原作者应发布更多代码,因为问题可能可以更优雅地解决,并符合函数式编程的最佳实践(例如使用findAny()
)。 - Brad