【发布时间】:2015-10-21 17:30:12
【问题描述】:
tldr:如何同时在多个(只读)Java HashMap 中搜索条目?
长版:
我有几个不同大小的字典存储为HashMap< String, String >。一旦它们被读入,它们就永远不会被改变(严格只读)。
我想检查是否以及哪个字典使用我的密钥存储了一个条目。
我的代码最初是在寻找这样的密钥:
public DictionaryEntry getEntry(String key) {
for (int i = 0; i < _numDictionaries; i++) {
HashMap<String, String> map = getDictionary(i);
if (map.containsKey(key))
return new DictionaryEntry(map.get(key), i);
}
return null;
}
然后它变得更复杂了:我的搜索字符串可能包含拼写错误,或者是存储条目的变体。就像,如果存储的密钥是“香蕉”,我可能会查找“香蕉”或“香蕉”,但仍然希望返回“香蕉”的条目。使用 Levenshtein-Distance,我现在遍历所有字典和其中的每个条目:
public DictionaryEntry getEntry(String key) {
for (int i = 0; i < _numDictionaries; i++) {
HashMap<String, String> map = getDictionary(i);
for (Map.Entry entry : map.entrySet) {
// Calculate Levenshtein distance, store closest match etc.
}
}
// return closest match or null.
}
到目前为止,一切正常,我得到了我想要的条目。不幸的是,我必须在五个不同大小的字典(约 30 - 70k 个条目)中查找大约 7000 个字符串,这需要一段时间。从我的处理输出来看,我有一个强烈的印象,我的查找支配了整个运行时间。
我改进运行时的第一个想法是并行搜索所有字典。由于不需要更改任何字典,并且同时访问字典的线程不超过一个,因此我看不到任何安全问题。
问题只是:我该怎么做?我以前从未使用过多线程。我的搜索只找到了 Concurrent HashMaps(但据我所知,我不需要这个)和 Runnable 类,我必须将我的处理放入方法 run() 中。我想我可以重写我当前的类以适应 Runnable,但我想知道是否有更简单的方法可以做到这一点(或者我怎么能简单地用 Runnable 来做到这一点,现在我有限的理解认为我必须重组很多)。
自从我被要求分享 Levenshtein-Logic:这真的没什么花哨的,但是给你:
private int _maxLSDistance = 10;
public Map.Entry getClosestMatch(String key) {
Map.Entry _closestMatch = null;
int lsDist;
if (key == null) {
return null;
}
for (Map.Entry entry : _dictionary.entrySet()) {
// Perfect match
if (entry.getKey().equals(key)) {
return entry;
}
// Similar match
else {
int dist = StringUtils.getLevenshteinDistance((String) entry.getKey(), key);
// If "dist" is smaller than threshold and smaller than distance of already stored entry
if (dist < _maxLSDistance) {
if (_closestMatch == null || dist < _lsDistance) {
_closestMatch = entry;
_lsDistance = dist;
}
}
}
}
return _closestMatch
}
【问题讨论】:
-
我建议研究更好的数据分区。对于 Trie 结构来说,这听起来不错。
-
在考虑树时,我想您的意思是如果寻找“香蕉”,我只会考虑以“B”开头的条目,对吧?但是如果我的钥匙是“香蕉”呢?我将如何获得任何点击?
-
您愿意提供您的
Levenshtein distance逻辑吗?可能有助于减少运行时间 -
@Babel:我编辑了我的文本并添加了 Levenshtein 距离。计算不是我自己写的,只是用了
StringUtils。
标签: java multithreading dictionary hashmap