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

How do I check if a specific value is in a given list of values?

I’m looking for the Java equivalent of C#’s new[] { 0, 2, 3, 5, 6, 7, 8, 9 }.Contains(digit).

I know I can use something like this, but I’d rather use something more concise:

if (digit == 0 || digit == 2 || digit == 3 || digit == 5 || digit == 6 || digit == 7 || digit == 8 || digit == 9)
{
}

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

>Solution :

If you want to search in a List:

List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);

call contains() method but its complexity is O(n).

nums.contains(searchNumber);

If you want to search in a Set:

Set<Integer> nums = new HashSet<>();
nums.add(1);
nums.add(2);
nums.add(3);
nums.add(4);
nums.contains(searchNumber);

here contains() runs in O(1) which is better than O(n).

Overall, it depends on how many elements your collection will store. If a collection is small, using a HashSet can be overhead.

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