Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Canonical way to test if value is among values in Java

Python:

if a in (b, c, d):
   ...

JavaScript:

if ([b, c, d].contains(a)) {
    ...
}

What is the canonical syntax for doing this in Java ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The goals are:

  • Test if a given value is equal to any among a set of other values
  • The set of values should be forgotten as soon as the if’s condition is done being evaluated – so, everything should be contained in the if’s parentheses
  • Execution should be cheap
  • The variable to test (here, a) should not be repeated

EDIT : ideally a solution compatible with Java 8 gains bonus points

EDIT2 : the question marked as a duplicate does not try to satisfy the second goal listed above, and it’s accepted answer does not satisfy it either (since it declares a constant).

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading