Mridang Agarwalla Mridang Agarwalla - 6 months ago 24
Java Question

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

In an

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.

static final List<String> fruit = Arrays.asList("APPLE", "ORANGES", "GRAPES");

if (fruit.contains(fruitname))

If your list was much larger, a set would be more efficient.

static final Set<String> fruit = new HashSet<String>(
       Arrays.asList("APPLE", "ORANGES", "GRAPES", /*many more*/));