[英]Java map values of List into a Hashmap
I have a HashMap: 我有一个HashMap:
K1, false
K2, false
K3, false
...
K1000, false
Initially all the values of keys are false. 最初,所有键的值均为false。
I have an ArrayList: 我有一个ArrayList:
K3, K10, K33,..., K417, K834, K998
I need to get the values of the list and mark just those values as "true" in the Hashmap for the corresponding keys. 我需要获取列表的值,并在Hashmap中将相应键仅将这些值标记为“ true”。 Now I know we can do this:
现在我知道我们可以做到这一点:
Iterate HashMap:
Iterate List:
if HashMap.contains(List[i])
HashMap.put(List[i], true)
But we are using 2 iterations in this logic and maybe for 1000 keys it is not much of a problem, but if I want to scale it to a million keys, is there any efficient algorithm I can use to achieve above? 但是我们在这种逻辑中使用了2次迭代,也许对于1000个键来说这不是什么大问题,但是如果我想将其扩展到一百万个键,那么有什么有效的算法可以用来实现上述目标?
Thanks. 谢谢。
You don't need to iterate HashMap
explicitly. 您不需要显式地迭代
HashMap
。 hashMap.containsKey(key)
checks if a key present in the map or not in an optimized way. hashMap.containsKey(key)
检查hashMap.containsKey(key)
是否以优化方式存在于地图中。 You need to study a bit on how HashMap works. 您需要研究一下HashMap的工作方式。
Iterate List:
if HashMap.containsKey(List[i])
HashMap.put(List[i], true)
This will work. 这将起作用。
Use Map.replace()
: 使用
Map.replace()
:
for (E element : list) {
map.replace(element, true);
}
This will only update existing keys with matching elements in list
. 这只会更新
list
具有匹配元素的现有键。
As a side note, a Map<K, Boolean>
can often be replaced by a lighter Set<K>
. 附带说明一下,
Map<K, Boolean>
通常可以用较轻的Set<K>
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.