简体   繁体   English

使用HashMap搜索功能

[英]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 如果您不想维护键值对,请考虑使用java.util.HashSet

I assume your main use case would be adding elements to it and then calling 'contains' which has O(1) complexity 我假设您的主要用例是在其中添加元素,然后调用具有O(1)复杂度的“包含”

Why do you need a HashMap for this? 为什么为此需要HashMap? There are a few ArrayList Examples for this. 有一些ArrayList示例。

ArrayList , List , LinkedList ArrayListListLinkedList

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. LinkedList<String>此列表现在存储字符串值。

or as the comments suggested you can use a HashSet 或如建议的注释,您可以使用HashSet

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

You can go with HashSet . 您可以使用HashSet contains(Object o) method can help you in doing desired operation. contains(Object o)方法可以帮助您完成所需的操作。 It returns true if element is present otherwise returns false . 它返回true ,如果元素存在,否则返回false

You can use Bloom Filter. 您可以使用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. 关于Bloom Filters的很酷的文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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