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:
a
) should not be repeated, as it may be an expensive or side-effected expression rather than a variableI 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.
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