Is there a simpler way to check multiple values against one value in an if-statement?
You can do the following in plain java
Arrays.asList(a, b, c, d).contains(x);
Unfortunately there is no such construct in Java.
It this kind of comparison is frequent in your code, you can implement a small function that will perform the check for you:
public boolean oneOfEquals(int a, int b, int expected) {
return (a == expected) || (b == expected);
}
Then you could use it like this:
if(oneOfEquals(a, b, 0)) {
// ...
}
If you don't want to restrict yourselft to integers, you can make the above function generic:
public <T> boolean oneOfEquals(T a, T b, T expected) {
return a.equals(expected) || b.equals(expected);
}
Note that in this case Java runtime will perform automatic boxing and unboxing for primitive types (like int
), which is a performance loss.
As referenced from this answer:
In Java 8+, you might use a
Stream
andanyMatch
. Something likeif (Stream.of(b, c, d).anyMatch(x -> x.equals(a))) { // ... do something ... }
Note that this has the chance of running slower than the other if checks, due to the overhead of wrapping these elements into a stream to begin with.