我想知道从java流设置布尔标志值的最佳实践是什么.这是我想要做的一个例子:
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
Run Code Online (Sandbox Code Playgroud)
但是,这违反了语言限制"lambda表达式中使用的变量应该是最终的或有效的最终结果".我能想到一些解决方案,但我不确定哪种解决方案最好.我的第一个解决方案是添加与condition列表匹配的元素并进行检查List::isEmpty.人们还可以包裹flag一个AtomicReference.
请注意,我的问题类似于这个问题,但我试图在最后提取一个布尔值而不是设置一个变量.