基于条件设置对象值并使用java 8流返回布尔值 [英] Based on condition set object value and return boolean using java 8 streams
问题描述
我有嵌套列表,如果条件为真,我可以设置isMatched和department.setMatchedStatus(true)。
I have nested list and am able to set isMatched and department.setMatchedStatus(true) when if condition is true.
boolean isMatched = false;
for (Employee employee: company.getEmployees()) {
for (Department department: employee.getDepartments()) {
if(departmentList.contains(department.getDepartmentName())){
isMatched = true;
department.setMatchedStatus(true);
}
}
}
return isMatched;
想要使用java 8流实现相同的功能,我尝试使用下面的代码,但是不能t返回布尔值。
Would like to achieve the same using java 8 streams, which i tried using below code, but couldn't return boolean.
isMatched = company.getEmployees().stream()
.flatMap(employee-> employee.getDepartments().stream())
.filter((department) -> departmentList.contains(department.getDepartmentName()))
.forEach((department) -> department.setMatchedStatus(true));
有人可以帮我吗?
推荐答案
这里的难点在于你有两个你想要执行的副作用:在 Department
对象上设置匹配状态,并设置一个本地标志值,用于确定是否存在任何匹配。在 peek 和计算
的方法/ 1441122> sisyphus'回答将起作用,因为在这种情况下我们可以确保 count
不会短路。但是,它可能会导致维护问题。如果有人复制并重新安排这些代码,它可能会因为短路而无声地破坏,这将是非常微妙的。
The difficulty here is that you have two side effects you want performed: setting the matched state on the Department
object, and setting a local flag value to determine if there were any matches. The approach of using peek
and count
in sisyphus' answer will work, since in this case we can be assured that count
won't short-circuit. However, it may cause problems under maintenance. If somebody were to copy and rearrange this code, it might silently break because of short-circuiting, and this would be quite subtle.
也许更好的方法是打包副作用进入 forEach
操作。这使用 AtomicBoolean
作为可变框来解决无法改变捕获的局部变量的问题。它也优于单元素数组技巧,因为在并行运行流时,原子是安全的。
Perhaps a better approach is to pack the side effects into the forEach
operation. This uses AtomicBoolean
as a mutable "box" to work around the inability to mutate captured local variables. It's also preferable to the single-element array trick, as the atomics are safe in case the stream is run in parallel.
这也使用了一个语句lambda,我通常更愿意避免。在这种情况下,它并不太糟糕,并且表明正在发生多种副作用。
This also uses a statement lambda, which I generally prefer to avoid. In this case it's not too bad, and it makes clear that multiple side effects are occurring.
AtomicBoolean isMatched = new AtomicBoolean(false);
company.getEmployees().stream()
.flatMap(employee -> employee.getDepartments().stream())
.filter(department -> departmentList.contains(department.getDepartmentName()))
.forEach(department -> {
department.setMatchedStatus(true);
isMatched.set(true);
});
return isMatched.get();
这篇关于基于条件设置对象值并使用java 8流返回布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!