简体   繁体   English

是否存在用于存储布尔表达式的数据结构?

[英]Is there a data structure for storing boolean expressions?

I need to store Boolean expressions like this: 我需要存储这样的布尔表达式:

x1 AND x2 AND x3 OR (x4 AND x5) AND (NOT x6)

Each x variable is a Boolean expression like == or != with values. 每个x变量都是一个布尔表达式,如==!= with values。 The problem is to store nested AND and OR clauses (inside themselves and/or inside each other) and wrap them with NOT . 问题是存储嵌套的ANDOR子句(在自身内部和/或彼此内部)并用NOT包装它们。 The wrapping depth can be very deep. 包裹深度可以非常深。

Does the Java SDK have data structure for these expressions? Java SDK是否具有这些表达式的数据结构?

In Java 8 the functional interface Predicate<T> is the way to go. 在Java 8中,功能接口Predicate<T>是要走的路。

Here are the Java docs . 这是Java文档

And here are various examples . 以下是各种例子

So in your use case it will be something as follows: 所以在你的用例中它将是如下:

public static Predicate<Integer> equals(Integer compare) {
    return i -> i.equals(compare);
}

public static Predicate<Integer> complex() {
    return equals(1).and(equals(2)).and(equals(3)).or(equals(4).and(equals(5))).and(equals(6).negate());
}

Remember — only Java 8 onwards! 记住 - 只有Java 8以上!

You can try to use jexl ( http://commons.apache.org/jexl/ ) 您可以尝试使用jexl( http://commons.apache.org/jexl/

JexlEngine jexl = new JexlEngine();
    jexl.setSilent(true);
    jexl.setLenient(true);

    Expression expression = jexl.createExpression("(a || b && (c && d))");
    JexlContext jexlContext = new MapContext();

    //b and c and d should pass
    jexlContext.set("b",true);
    jexlContext.set("c",true);
    jexlContext.set("d",true);

    assertTrue((Boolean)expression.evaluate(jexlContext));

    jexlContext = new MapContext();

    //b and c and NOT d should be false
    jexlContext.set("b",true);
    jexlContext.set("c",true);

    //note this works without setting d to false on the context
    //because null evaluates to false

    assertFalse((Boolean)expression.evaluate(jexlContext));

Example from this question 这个问题的例子

ps: It is not included in standard sdk but quite easy to use. ps:它不包含在标准sdk中,但非常容易使用。

abstract class Predicate {...}
class AndPredicate extends Predicate {
  private Predicate[] conjuncts;
  ...
}
class OrPredicate extends Predicate {
  private Predicate[] disjuncts;
  ...
}
class NotPredicate extends Predicate {
  Predicate negated;
  ...
}

What is the problem? 问题是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM