Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an element exists in a Set of items?

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.

like image 252
Mridang Agarwalla Avatar asked Jan 14 '11 08:01

Mridang Agarwalla


People also ask

How do you check if something exists in a set?

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.

How do you check if an element exists in a set in Java?

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.

How do you check if a list contains a value in Java?

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.


1 Answers

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*/)); 
like image 145
Peter Lawrey Avatar answered Sep 20 '22 21:09

Peter Lawrey