I am modifying an object using 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... i.e, 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.
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.
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. I'd write the above in a unit test for validation purposes, but not in production code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With