我有两个 HashMap,想尽快比较它,但问题是,mapA 的字符串由两个以空格连接的单词组成。 mapB的String只有一个单词。
我不想计算出现次数,这已经完成了,我想比较两个不同的字符串
mapA:
key: hello world, value: 10
key: earth hi, value: 20
mapB:
key: hello, value: 5
key: world, value: 15
key: earth, value: 25
key: hi, value: 35
mapA 的第一个键应该从 mapB 中找到键“hello”和键“world”
我想做的是解析一个长文本以查找同时出现的情况,并设置它们与所有单词相关的出现频率的值。
我的第一次尝试:
for(String entry : mapA.keySet())
{
String key = (String) entry;
Integer mapAvalue = (Integer) mapA.get(entry);
Integer tokenVal1=0, tokenVal2=0;
String token1=key.substring(0, key.indexOf(" "));
String token2=key.substring(key.indexOf(" "),key.length()).trim();
for( String mapBentry : mapb.keySet())
{
String tokenkey = mapBentry;
if(tokenkey.equals(token1)){
tokenVal1=(Integer)tokens.get(tokenentry);
}
if(tokenkey.equals(token2)){
tokenVal2=(Integer)tokens.get(tokenentry);
}
if(token1!=null && token2!=null && tokenVal1>1000 && tokenVal2>1000 ){
**procedurecall(mapAvalue, token1, token2, tokenVal1, tokenVal2);**
}
}
}
最佳答案
如果您只是想查找特定键,则不应迭代 HashMap
(O(n)),这就是 HashMap
查找 (O(1)) 的用途。所以消除你的内部循环。
您还可以消除代码中一些不必要的变量(例如key
、tokenkey
)。您也不需要第三个 tokens
映射,您可以将标记值放入 mapb
中。
for(String entry : mapA.keySet())
{
Integer mapAvalue = (Integer) mapA.get(entry);
String token1=entry.substring(0, entry.indexOf(" "));
String token2=entry.substring(entry.indexOf(" "),entry.length()).trim();
if(mapb.containsKey(token1) && mapb.containskey(token2))
{
// look up the tokens:
Integer tokenVal1=(Integer)mapb.get(token1);
Integer tokenVal2=(Integer)mapb.get(token2);
if(tokenVal1>1000 && tokenVal2>1000)
{
**procedurecall(mapAvalue, token1, token2, tokenVal1, tokenVal2);**
}
}
关于java - 通过不同的字符串键比较 Hashmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42257784/