How to implement a Predicate in Java used for cross-checking a String against an arbitrary amount of rules?

青春壹個敷衍的年華 提交于 2019-12-08 00:12:23

问题


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 ...).


回答1:


You could just have the following:

private boolean capitalize(String word) {
    Stream<Predicate<String>> stream = Stream.of(this::isNoun, this::isVerb, this::isParticiple); 
    return stream.anyMatch(rule -> rule.test(word));
}

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.




回答2:


An alternative approach would be to form a composite predicate, then apply it:

Predicate<String> capitalize = Stream.<Predicate<String>>of(this::isNoun, 
                  this::isVerb, 
                  this::isParticiple)
        .reduce(Predicate::or).orElse(s -> false);

/** PRIMARY METHODS **/
private boolean capitalize(String word) {
    return capitalize.test(word);
}

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.



来源:https://stackoverflow.com/questions/33986324/how-to-implement-a-predicate-in-java-used-for-cross-checking-a-string-against-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!