自定义规则筛选器

这是一个解析方法,用以解析由().and.or组成的表达式, (你也可以自己添加规则)
如果想用数学上的带有()组合的表达式一样来处理与或操作
那么这个方法完全适合. _
例如你需要对以下规则进行数据过滤:
(region = “asia”) AND ((status = null) OR ((inactive = “true”) AND (department = “aaaa”)) OR ((costcenter = “ggg”) OR (location = “india”)))

处理流程介绍

现在有一批学生数据, 我想要筛选其中的女学生, 并且成绩都及格的, 或者是喜欢篮球的男生, 那么我们规定的规则如下:

((student.sex=0) and (student.score > 60) ) or ((student.sex=1) and (student.hobbies='basketball'))
  • 解析后的单条规则:
    @1: student.sex=0
    @2: student.score > 60
    @3: @1 and @2
    @4: student.sex=1
    @5: student.hobbies=‘basketball’
    @6: @4 and @5
    @7: @3 or @6
  • 根据每个单规则, 生成规则函数, 例如
Predicate<Student> = 
student -> {
    if (student.sex==0) {
        return true;
     }else{
       return false;
       }
};
  • 将规则函数整合为最终的规则, 最终只会有一个规则函数
    例如and符
// and规则函数集合
List<Predicate<Student>> mappers;
// 合并后的规则函数
Predicate<Student> = 
student -> mappers.stream()
  .reduce(t ->true, Predicate::and)
  .test(student);
  • 对数据进行过滤

规则解析器


import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 这是一个解析方法,用以解析由().and.or组成的表达式
 * 如果想用数学上的带有()组合的表达式一样来处理与或操作
 * 那么这个方法完全适合. ~_~
 *
 * this is a common function of parsing str expression which combined by (). and . or .,
 * if you want to operate the str like a mathematical expression,
 * this is method is nice for you
 *
 * @author lycaon
 * @date 05-29
 * @version 1.0.0
 */
public class FilterCommandParser {
    private static final Pattern BRACED_REDUX = Pattern.compile("\\(([^()]*)\\)");

    /**
     * <pre>
     * String exp = "(region = "asia") AND ((status = null) OR ((inactive = "true") AND (department = "aaaa")) OR ((costcenter = "ggg") OR (location = "india")))";
     * List<String> decodedExp = parse(exp);
     * for (int i = 0; i < decodedExp.size(); ++i) {
     *             System.out.println("@%d = %s%n", i, decodedExp.get(i));
     * }
     * decodeExp:
     *      @0 = region = "asia"
     *      @1 = status = null
     *      @2 = inactive = "true"
     *      @3 = department = "aaaa"
     *      @4 = @2 AND @3
     *      @5 = costcenter = "g
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值