简体   繁体   中英

Using a HashMap for search capabilites

I need to use a data structure that can provide a low search time, but don't have a need to store key, value pairs.

All I need is to check if an element exists in a collection or not.

I'm thinking of inserting all the values from an array into a hashmap (with the key and value being the same) and then perform search operations on this.

Any alternatives or is this reasonable?

If you don't want to maintain key-value pairs, consider using java.util.HashSet

I assume your main use case would be adding elements to it and then calling 'contains' which has O(1) complexity

Why do you need a HashMap for this? There are a few ArrayList Examples for this.

ArrayList , List , LinkedList

You can define the object you want to store in the List by using the diamond operator

LinkedList<String> this list now stores String values.

or as the comments suggested you can use a HashSet

HashSet<String> hashSet = new HashSet<>();
hashSet.add("Item");

You can go with HashSet . contains(Object o) method can help you in doing desired operation. It returns true if element is present otherwise returns false .

You can use Bloom Filter. it is used to test whether an element is a member of a set. False positive matches are possible, but false negatives are not – in other words, a query returns either "possibly in set" or "definitely not in set". Elements can be added to the set, but not removed (though this can be addressed with a "counting" filter); the more elements that are added to the set, the larger the probability of false positives.

Cool article on Bloom Filters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM