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

ぐ巨炮叔叔 提交于 2019-12-06 08:27:05

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.

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.

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