Reputation: 1899
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?
Upvotes: 0
Views: 59
Reputation: 1
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.
Upvotes: 0
Reputation: 2592
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
.
Upvotes: 0
Reputation: 42441
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
Upvotes: 4
Reputation: 3154
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");
Upvotes: 2