In an if
statement in Java how can I check whether an object exists in a set of items. E.g. In this scenario i need to validate that the fruit will be an apple, orange or banana.
if (fruitname in ["APPLE", "ORANGES", "GRAPES"]) { //Do something }
It's a very trivial thing but I couldn't figure out a short and concise way to accomplish this.
To check if a given value exists in a set, use .has() method: mySet.has(someVal); Will return true if someVal appears in the set, false otherwise.
Set contains() method in Java with Examples Set. contains() method is used to check whether a specific element is present in the Set or not. So basically it is used to check if a Set contains any particular element.
contains() method can be used to check if a Java ArrayList contains a given item or not. This method has a single parameter i.e. the item whose presence in the ArrayList is tested. Also it returns true if the item is present in the ArrayList and false if the item is not present.
static final List<String> fruits = Arrays.asList("APPLE", "ORANGES", "GRAPES"); if (fruits.contains(fruitname))
If your list was much larger, a set would be more efficient.
static final Set<String> fruits = new HashSet<String>( Arrays.asList("APPLE", "ORANGES", "GRAPES", /*many more*/));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With