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 variable to test (here,
a) should not be repeated
EDIT : ideally a solution compatible with Java 8 gains bonus points
EDIT2 : the question marked as a duplicate does not try to satisfy the second goal listed above, and it’s accepted answer does not satisfy it either (since it declares a constant).
>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