如何检查一组项目中是否存在元素? [英] How can I check if an element exists in a Set of items?
本文介绍了如何检查一组项目中是否存在元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java中的 if
语句中,如何检查对象是否存在于一组项目中。例如。
在这种情况下,我需要验证水果是苹果,橙子还是香蕉。
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.
推荐答案
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*/));
这篇关于如何检查一组项目中是否存在元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文