Mridang Agarwalla
Mridang Agarwalla

Reputation: 45128

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.

Upvotes: 50

Views: 120901

Answers (4)

Peter Lawrey
Peter Lawrey

Reputation: 533880

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*/));

Upvotes: 73

lukastymo
lukastymo

Reputation: 26809

If you have Set, List, Map of fruits which all have the same parent: Collection, you can try this example.

String fruitName = "Orange";
Collection<String> fruits = ... // set of fruits
if (fruits.contains(fruitName)) {
    ...
}

(For Java 8/9/10 ways of creating literal Set please see this SO answer.)

Be careful with case sensitivity (Orange != orange).

Upvotes: 1

extraneon
extraneon

Reputation: 23980

Is Arrays.binarySearch what you are looking for?

String [] fruits = new String[]{"APPLE", "ORANGES", "GRAPES"};
Arrays.sort(fruits); // binarySearch requires that the array is sorted

if (Arrays.binarySearch(fruits), fruitname) >= 0) {
  // found!
}

And of course the trusted Apache Commons ArrayUtils:

if (ArrayUtils.contains(new String[]{"APPLE", "ORANGES", "GRAPES"}, fruitname){
  // found
}

I knew there would be something in Apache Commons :)

Upvotes: 2

Gareth Davis
Gareth Davis

Reputation: 28069

for completeness using google-collections/guava:

import com.google.common.collect.Sets;

static final Set<String> fruit = Sets.newHashSet("APPLE", "ORANGES", "GRAPES");

if (fruit.contains(fruitname))

or using the plane old jdk classes:

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

Upvotes: 11

Related Questions