Search code examples
java

Canonical way to test if value is among values in Java


Python:

if a in (b, c, d):
   ...

JavaScript:

if ([b, c, d].contains(a)) {
    ...
}

What is the canonical syntax for doing this in Java ?

The goals are:

  • Test if a given value is equal to any among a set of other values
  • The set of values should be forgotten as soon as the if's condition is done being evaluated - so, everything should be contained in the if's parentheses
  • Execution should be cheap
  • The value to test against (here, a) should not be repeated, as it may be an expensive or side-effected expression rather than a variable

I am ideally looking for a solution compatible with Java 8.

Because of the second point above, which as a reminder is that the set of values should be forgotten as soon as the if's condition is done being evaluated, CONSTANT.contains() is not a solution, since the nature of a constant means it 1) is calculated long before arriving to the if statement, 2) persists after the condition is evaluated.

The question currently marked as duplicate to this one asks how to test among constants, which this question is not about.


Solution

  • Something like this would work in Java 8

    I used string for simplicity but any type that implements a comparison operator would work

    if(Arrays.asList("a", "b", "c").contains("a")) {
       //Code
    }
    

    This would be a linear search in O(n) time which is also what you have in the examples you gave