This question is a continuation of: How to check whether an input conforms to an arbitrary amount of rules in Java?
I'm trying to make use of Predicates to cross-check a string/word against a set of rules/methods that return a boolean value. However I'm having difficulties implementing it in my code.
public class CapValidator {
/** PRIMARY METHODS **/
private boolean capitalize(String word) {
// boolean valid = true;
// for (Predicate<> rule : rules) {
// valid = valid && rule.test(word);
// }
return false;
}
/** SUPPORT METHODS **/
private boolean isNoun(String word) {
// do some logic
}
private boolean isVerb(String word) {
// do some logic
}
private boolean isParticiple(String word) {
// do some logic
}
}
Any suggestions on how I can implement capitalize(String)
? It should check whether the word conforms to a set of rules (the word is a noun or a verb or a participle or ...).
You could just have the following:
This create a Stream of 3 rules to check and reduces them to a single value by
||
ing every result. The advantage is that if you need to add more rules, you just need to update the Stream declaration.However, another (simpler) solution might also be to not use Streams and just write a series of
||
for every method.An alternative approach would be to form a composite predicate, then apply it:
Here the Stream of predicates is reduced using
Predicate.or()
method. You can do this only once. After that you just apply the compound predicate.