3

I have a variable having some numeric value x = 5;.

I want to right an expression like:

if arr = [4,7,10] contains x in mvel.

Is that possible, if yes, how ?

As of now I will have to right expression as :

x == 4 || x == 7 || x == 10

but since i may have a big list can this be made something like

x in [4,7,10,...]

Code :

for(Rule rule: ruleList)
{
    String expresssion = rule.getConditionExpression();
    boolean result = (Boolean) expressionHandler.execute(expresssion,ruleEvalData);

}

Here expression will be like :

expression = 'x == 4 || x == 7 || x == 10';

and ruleEvalData will have x in it.

I want to know if

expression ='x in [4,7,10,...]' is possible in MVEL ?

GP007
  • 601
  • 1
  • 8
  • 22

3 Answers3

2

You want to use the MVEL contains operator. You can construct the list of values to test against using the literal List syntax.

[4,7,10] contains x

Oddly enough, I can't find documentation of the contains operator in MVEL's documention page, but it exists in the code and calls the standard Collection.contains() method.

1

Use java.util.stream.IntStream class:

int[] array = {4, 7, 10};
boolean exist = IntStream.of(array).anyMatch(x -> x == 5);

This will return true if any elements of this stream of(array) match the provided predicate, false otherwise.

DimaSan
  • 10,315
  • 10
  • 56
  • 68
  • Hi, My main query is can i define this int[] array in mvel expression? Also I dont need to pass x here as it is a variable from my java code and will be populated at runtime. – GP007 Aug 29 '16 at 19:31
  • Yes, you can use any value instead of literal `5`. – DimaSan Aug 29 '16 at 19:34
  • But you can not declare int[] array in expression itself – GP007 Aug 29 '16 at 19:35
1

Another option

Integer[] array = {4, 7, 10};
boolean exist = Arrays.asList(array).contains(5);
tnas
  • 474
  • 5
  • 14