[英]How to modify and check if modified in java - 8?
I am modifying an object using java-8 我正在使用java-8修改对象
users.stream().filter(u -> u.count > 0).forEach(u -> u.setProperty("value"))
However, I want to understand if any object was modified or not... ie, I want a boolean return value, while this is void. 但是,我想了解是否有任何对象被修改...即,我想要一个布尔返回值,而这是无效的。
Any way to do it? 有办法吗?
If I get you correctly, you want to know whether there were any matches while performing the operation. 如果我找到你,你想知道在执行操作时是否有任何匹配。 You could simply use two statements.
你可以简单地使用两个语句。
boolean anyMatch = users.stream().anyMatch(u -> u.count > 0);
if(anyMatch) users.stream().filter(u -> u.count > 0).forEach(u -> u.setProperty("value"));
Since anyMatch
stops at the first matching element, there would be redundant work only if there is a long prefix of non-matching elements before the first match. 由于
anyMatch
在第一个匹配元素anyMatch
停止,因此只有在第一个匹配之前存在非匹配元素的长前缀时才会有冗余工作。
If that's a concern, you could use 如果这是一个问题,你可以使用
Spliterator<User> sp = users.stream().filter(u -> u.count > 0).spliterator();
boolean anyMatch = sp.tryAdvance(u -> u.setProperty("value"));
sp.forEachRemaining(u -> u.setProperty("value"));
instead. 代替。
Since this is a consuming operation, it can only ever be used with methods that don't actually return anything back; 由于这是一个消耗操作,它只能用于实际上没有返回任何东西的方法; that is, using
forEach
ensures a terminal operation in which you don't get a return value back. 也就是说,使用
forEach
可确保终止操作,在该操作中您不会返回返回值。
If you want to validate that the property is set the way you want it to be, you'd have to check the elements again. 如果要验证属性是否按照您希望的方式设置,则必须再次检查元素。
users.stream().filter(u -> u.count > 0)
.allMatch(u -> u.getProperty().equals("value"));
Although this speaks more to paranoia than anything else; 虽然这比偏执狂更能说明偏执狂; unless
setProperty
has some other side effect which isn't exposed here , then the setter should always set the value. 除非
setProperty
具有其他未在此处公开的副作用,否则setter应始终设置该值。 I'd write the above in a unit test for validation purposes, but not in production code. 我在单元测试中编写以上内容以进行验证,但不在生产代码中。
Add a call to peek()
: 添加对
peek()
的调用:
AtomicBoolean modified = new AtomicBoolean();
users.stream()
.filter(u -> u.count > 0)
.peek(u -> modified.set(true))
.forEach(u -> u.setProperty("value"))
If any elements make it through the filter, modified.get()
will return true
. 如果任何元素通过过滤器,
modified.get()
将返回true
。
The use of AtomicBoolean
(or something similar) is required because references used in lambdas must be effectively final . 需要使用
AtomicBoolean
(或类似的东西),因为lambdas中使用的引用必须是有效的final 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.