简体   繁体   English

MVEL'in'运算符不适用于java中的集合

[英]MVEL 'in' operator not working for collections in java

I'm trying to use MVEL 'in' operator in my code to evaluate an expression 我正在尝试在我的代码中使用MVEL'in'运算符来计算表达式

List<String> countriesAvailable = new ArrayList<String>();
countriesAvailable.add("Australia");
countriesAvailable.add("France");
List<String> countriesVisited = new ArrayList<String>();
countriesVisited.add("Austria");
countriesVisited.add("France");
Map<String, List<String>> vars = new HashMap<String, List<String>>();
vars.put("countriesAvailable", countriesAvailable);
vars.put("countriesVisited", countriesVisited);
Boolean s = (Boolean) MVEL.eval("countriesVisited in countriesAvailable", vars);
System.out.println(s);

Gives Error: syntax error or incompatible types 给出错误:语法错误或不兼容的类型

Here is the solution. 这是解决方案。 You need to use containsAll 你需要使用containsAll

Also note that you misspelled Australia in the second list. 另请注意,您在第二个列表中拼错了澳大利亚。 I'm not sure if that was on purpose to check the evaluation. 我不确定这是否有意检查评估。

    List<String> countriesAvailable = new ArrayList<String>();
    countriesAvailable.add("Australia");
    countriesAvailable.add("France");

    List<String> countriesVisited = new ArrayList<String>();
    countriesVisited.add("Austria");
    countriesVisited.add("France");

    Map<String, List<String>> vars = new HashMap<String, List<String>>();
    vars.put("countriesAvailable", countriesAvailable);
    vars.put("countriesVisited", countriesVisited);

    Boolean s = (Boolean) MVEL.eval(
            "countriesAvailable.containsAll(countriesVisited)", vars);

    System.out.println("Result = " + s);

Result = false

You can also use the java.util.Collections to perform a disjoint. 您还可以使用java.util.Collections执行不相交。 And take the negative of that. 并采取消极的态度。

Boolean s = 
   (Boolean) MVEL.eval(
         "!java.util.Collections.disjoint(countriesAvailable,countriesVisited)",
         vars);

Result = true

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

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