Question

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?

Was it helpful?

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.

OTHER TIPS

With Java 9 (and later versions) around the corner and using Set as specified by @nneonneo, we can achieve membership test in one line like below:

Set.of(item1, item2, item3).contains(reqItem)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top