-->

Checking whether a element present in List using m

2019-07-18 04:32发布

问题:

I had a list with me. The list is like.

List<String> locations=new ArrayList<String>();
locations.add("California");
location.add("sydney");
location.add("Egypt");

Now I want to check in mvel whether this list contains California and Sydney. I thought I could use the below one but that is giving error.

     location contains "sydney","california"

How can I find whether a list contains multiple elements in mvel?

回答1:

This will work:

list.containsAll(["sydney", "california"])


回答2:

This works for me:

 //@Test
 public void testListContains() {
      List<String> locations = new ArrayList<String>();

     locations.add("California");
     locations.add("sydney");
     locations.add("Egypt");

     String expression = "thelocations contains acity && thelocations contains anothercity";

     Map container = new HashMap();

     container.put("thelocations", locations);

     container.put("acity", "sydney");

     container.put("anothercity","California");

     Object result = MVEL.eval(expression,container);

     System.out.println(result);
 }


回答3:

To simplify kvn's answer, you can embed cities you testing against within the expression. Just surround it with single quotes:

public void testListContains() {
    List<String> locations = new ArrayList<String>();
    locations.add("California");
    locations.add("sydney");
    locations.add("Egypt");

    String expression = "thelocations contains 'sydney' && thelocations contains 'California'";

    Map container = new HashMap();
    container.put("thelocations", locations);

    Object result = MVEL.eval(expression,container);

    System.out.println(result);
}


标签: java ognl mvel