Our objects have "properties"; and their current state is represented as Map<String, Object>
where the key resembles the name of the property. The values can have different types, my current task is only dealing with Boolean properties though.
Beyond the current status, also "updates" to objects are organized via such maps.
Now I have to prevent that a property that is currently true
gets disabled (turned to false
).
Using streams, this here works:
Set<String> currentlyEnabled = currentObjectPropertiesMap.
.entrySet()
.stream()
.filter(e -> Boolean.TRUE.equals(e.getValue()))
.map(Entry::getKey)
.collect(Collectors.toSet());
Set<String> goingDisabled = updatedObjectPropertiesMap
.entrySet()
.stream()
.filter(e -> Boolean.FALSE.equals(e.getValue()))
.map(Entry::getKey)
.collect(Collectors.toSet());
currentlyEnabled.retainAll(goingDisabled);
if (currentlyEnabled.isEmpty()) {
return;
} else {
throw new SomeExceptionThatKnowsAllBadProperties(currentlyEnabled);
}
The above code first fetches a set of all properties that are true
, then it separately collects all properties that will turn false
. And if the intersection of these two sets is empty, I am fine, otherwise error.
The above works, but I find it clumsy, and I dislike the fact that the currentlyEnabled
set is misused to compute the intersection.
Any suggestion how this can be done in a more idiomatic, but readable "stream-ish" way?
You can just select all key-value-pairs whose value is true
, and then via the key, check if the value from the "update"-map is false
.
Set<String> matches = currentObjectPropertiesMap
.entrySet()
.stream()
.filter(e -> Boolean.TRUE.equals(e.getValue()))
.map(Map.Entry::getKey)
.filter(k -> Boolean.FALSE.equals(
updatedObjectPropertiesMap.get(k)
))
.collect(Collectors.toSet());
if(!matches.isEmpty()) throw ...
One solution that does not include explicit set intersection could be:
Set<String> violatingProperties = new HashSet<String>();
for (Entry<String, Object> entry : currentObjectPropertiesMap.entrySet()) {
if (! (Boolean) entry.getValue()) {
continue;
}
if (! updatedObjectPropertiesMap.hasKey(entry.getKey())) {
continue;
}
if (! (Boolean) updatedObjectPropertiesMap.get(entry.getKey())) {
violatingProperties.add(entry.getKey());
}
}
if (violatingProperties.size() > 0) {
throw ...
}
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