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

后端 未结 4 662
无人及你
无人及你 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:46

    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 :)

提交回复
热议问题