Anthony Anthony - 1 year ago 67
Java Question

Best way to format multiple 'or' conditions in an if statement (Java)

A simple question but Google hasn't been helping much.

I have an if statement with many conditions (have to check for 10 or 15 constants to see if any of them are present.)

Instead of writing something like:

if (x == 12 || x == 16 || x == 19 || ...)

is there any way to format it like

if x is [12, 16, 19]?

Just wondering if there is an easier way to code this, any help appreciated.

*Edit: The answers have been very helpful, but I was asked to add more detail by a few people so I will do that to satiate their curiosity. I was making a date validation class that needed to make sure days were not > 30 in the months that have only 30 days (of which there are 4, I think) and I was writing an if statement to check things like this:

if (day > 30 && (month == 4 || month == 6 || month == 9 || month == 11))

I was just wondering if there was a faster way to code things like that - many of the answers below have helped :).

Answer Source

I use this kind of pattern often. It's very compact:

// Define a constant in your class. Use a HashSet for performance
private static final Set<Integer> values = new HashSet<Integer>(Arrays.asList(12, 16, 19));

// In your method:
if (values.contains(x)) {

A HashSet is used here to give good look-up performance - even very large hash sets are able to execute contains() extremely quickly.

If performance is not important, you can code the gist of it into one line:

if (Arrays.asList(12, 16, 19).contains(x))

but know that it will create a new ArrayList every time it executes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download