How to format multiple ‘or’ conditions in an if statement

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

Define a constant in your class:

private static final Set<Integer> VALUES = Set.of(12, 16, 19);    
// Pre Java 9 use: VALUES = new HashSet<Integer>(Arrays.asList(12, 16, 19));

In your method:

if (VALUES.contains(x)) {
    ...
}

Set.of() returns a HashSet, which performs very well even for very large sets.

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

if (Set.of(12, 16, 19).contains(x))

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

Leave a Comment

tech