Why does checking if a HashMap has a certain value take very long to execute within a for loop?

旧时模样 提交于 2019-12-05 15:59:03

Map.containsValue() will have a linear time as you are iterating blindly over all the map values. As per the method javadoc:

Returns true if this map maps one or more keys to the specified value. More formally, returns true if and only if this map contains at least one mapping to a value v such that Objects.equals(value, v). This operation will probably require time linear in the map size for most implementations of the Map interface.

To take advantage of a hash lookup you should check the keys with Map.containsKey():

if (!intermediateCipher.containsKey(possibleKey)) {
  ...
}

Map.containsValue() must check every map entry. That costs O(n) in the size of the map. Supposing that the number of duplicates does not exceed a fixed fraction of all keys generated, checking containsValue() on each iteration of your loop then costs an aggregate O(n2) in the number of keys generated. For a million keys that's awfully expensive.

Consider instead keeping an auxiliary Set of the keys stored so far, and testing membership in that set instead of directly testing the values in the Map.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!