How to implement a Predicate in Java used for cros

2019-05-23 01:34发布

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

2条回答
Lonely孤独者°
2楼-- · 2019-05-23 02:18

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.

查看更多
Root(大扎)
3楼-- · 2019-05-23 02:20

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.

查看更多
登录 后发表回答