Lan*_*234 4 java iteration hashmap
我目前正在使用2 for循环比较所有条目,但是我得到了重复的比较。因为HashMap没有排序,所以我不知道如何消除已经进行的比较。例如,我有类似的东西:
for(Entry<String, String> e1: map.entrySet())
{
for(Entry<String, String> e2: map.entrySet())
{
if (e1.getKey() != e2.getKey())
{
//compare e1.getValue() to e2.getValue()
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题在于,将第一个条目与第二个条目进行比较,然后将第三个条目进行比较,依此类推。但是,第二个条目将再次与第一个条目进行比较,依此类推。然后将第三个条目与第一个条目进行比较,然后将第二个条目与第四个条目进行比较,等等。是否有更好的方法来遍历HashMaps以避免进行重复比较?
附加信息:
To be more specific and hopefully answer your questions, the HashMap I have is storing file names (the keys) and file contents (the values) - just text files. The HashMap has been populated by traversing a directory that contains the files I will want to compare. Then what I am doing is running pairs of files through some algorithms to determine the similarity between each pair of files. I do not need to compare file 1 to file 2, and then file 2 to file 1 again, as I only need the 2 files to be compared once. But I do need every file to be compared to every other file once. I am brand new to working with HashMaps. agim’s answer below might just work for my purposes. But I will also try to wrap my brain around both Evgeniy Dorofeev and Peter Lawrey's solutions below. I hope this helps to explain things better.
如果您不小心,则消除重复项的成本可能至少比键的冗余比较的成本高。
您可以使用以下命令订购钥匙 System.identityHashCode(x)
for(Map.Entry<Key, Value> entry1: map.entrySet()) {
Key key1 = entry1.getKey();
int hash1 = System.identityHashCode(key1);
Value value1 = entry1.getValue();
for(Map.Entry<Key, Value> entry2: map.entrySet()) {
Key key2 = entry2.getKey();
if (key1 > System.identityHashCode(key2)) continue;
Value value2 = entry1.getValue();
// compare value1 and value2;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36024 次 |
| 最近记录: |