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

后端 未结 4 664
无人及你
无人及你 2021-02-06 21:57

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, ora

4条回答
  •  被撕碎了的回忆
    2021-02-06 22:44

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

    String fruitName = "Orange";
    Collection 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).

提交回复
热议问题