如何在Java中实现Predicate,用于针对任意数量的规则交叉检查String? [英] How to implement a Predicate in Java used for cross-checking a String against an arbitrary amount of rules?

查看:478
本文介绍了如何在Java中实现Predicate,用于针对任意数量的规则交叉检查String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是以下问题的延续:如何检查输入是否符合Java中任意数量的规则?

This question is a continuation of: How to check whether an input conforms to an arbitrary amount of rules in Java?

我正在尝试使用Predicates对一组返回布尔值的规则/方法交叉检查字符串/单词。
但是我在代码中实现它时遇到了困难。

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
    }

}

关于我如何的任何建议可以实现 capitalize(String)?它应检查该词是否符合一组规则(该词是名词或动词或分词或......)。

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

推荐答案

你可以拥有以下内容:

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

这会创建一个3流规则来检查并将它们减少为单个值按 || 输入每个结果。优点是,如果你需要添加更多规则,你只需要更新Stream声明。

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.

然而,另一个(更简单的)解决方案也可能是不使用Streams并为每种方法写一系列 ||

However, another (simpler) solution might also be to not use Streams and just write a series of || for every method.

这篇关于如何在Java中实现Predicate,用于针对任意数量的规则交叉检查String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆