Search code examples
javapythonsetmembership

Java equivalent of Python 'in' - for set membership test?


I want to check if an item exists in an item set.

I want to do this in java:

def is_item_in_set(item, item_set):
    return item in item_set

I've managed writing this:

boolean isItemInSet(String item, String[] itemSet) {
    for(int i =0; i < itemSet.length; ++i) {
        if(item.equals(itemSet[i])) {
            return true;
        }
    }
    return false;
}

Is there a better way for testing set-membership in Java?


Solution

  • You can't do it with a straight array, but you can with a Set<T> by calling .contains. If you feel like you will be doing a lot of isItemInSet calls, consider using Sets instead of arrays -- you will be much happier.

    For example, using a HashSet<T> makes isItemInSet an O(1) operation (on average). Set insertion and deletion are also similarly fast. Indeed, a HashSet<T> in Java is essentially the same as a Python set() (similar underlying concept and performance characteristics) -- you will see a big improvement in speed with many calls to query, insert or delete on the set.