I have a Map<MyObject, String> myMap and I want to filter it in two other maps.
What I would like my code to look(pseudo code) something like this.
newMap = filter(myMap, dontApplyNOT);
myMap = filter(myMap, NOT);
public Map<Object, String> filter(... myMap, NOT) {
return myMap.entrySet().stream().filter(entry -> NOT condition(entry)).collect();
}
For reasons I can not add Equals to the Object nor can I change the data structure.
I am expecting to inverse the condition dynamically so I would not have to duplicate the filtering function.
Since the choice is simply between "apply !
" and "don't apply !
", you can use a boolean
to represent this choice.
public Map<Object, String> filter(..., boolean invertCondition) {
return myMap.entrySet().stream()
.filter(entry -> condition(entry) != invertCondition)
.collect(...);
}
Note the expression condition(entry) != invertCondition
. This is the same as condition(entry)
if invertCondition
is false, and is the same as !condition(entry)
if invertCondition
is true.