我正在计算文件中的单词数,并将单词及其各自的计数加载到 HashMap 中。我已经对值进行了排序并使用它来检索我的 key :
public static String getKey(TObjectIntHashMap<String> hash, int value){
for(String s: hash.keySet()){
if(value == hash.get(s)){
key = s;
hash.remove(key);
return key;
}
}
我知道这是一种相当丑陋的方法,但这似乎是我开始工作的唯一方法。我完全知道双图的存在,但不想使用它。有任何想法吗?
最佳答案
稍微更有效的方法是使用迭代器,因为这可以避免单独查找键和值:
public static String getKey(TObjectIntHashMap<String> hash, int value){
TObjectIntIterator<String> iterator = hash.iterator();
while (iterator.hasNext()) {
iterator.advance();
if (iterator.value() == value) {
key = iterator.key();
iterator.remove();
return key;
}
}
}
关于java - 在不使用 BiMap 的情况下从 Hashmap 中的值检索键的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33246142/