We often have to check if a value is one of a given set of values. But we don’t want to write code like this:
if (value == SomeEnum.FOO || value == SomeEnum.BAR || value == SomeEnum.QUX) { ...
Some use a Set and write it like this:
if (Set.of(SomeEnum.FOO, SomeEnum.BAR, SomeEnum.QUX).contains(value)) { ...
But now the runtime has to create a Set
each time this line is run and it also has to call the method contains
. And it can’t even handle null
. In Java we have a much better alternative: The switch expression. You can use it like so:
if (switch (value) { case FOO, BAR, QUX -> true; default -> false; }) { ...