Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify and check if modified in java - 8?

Tags:

java

java-8

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?

like image 959
Tanvi Jaywant Avatar asked Dec 17 '22 23:12

Tanvi Jaywant


2 Answers

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.

like image 50
Holger Avatar answered Jan 01 '23 12:01

Holger


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.

like image 40
Makoto Avatar answered Jan 01 '23 12:01

Makoto