BrownRecluse
BrownRecluse

Reputation: 1670

Java map values of List into a Hashmap

I have a HashMap:

K1, false
K2, false
K3, false
...
K1000, false

Initially all the values of keys are false.

I have an 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. 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?

Thanks.

Upvotes: 0

Views: 138

Answers (2)

shmosel
shmosel

Reputation: 50716

Use Map.replace():

for (E element : list) {
    map.replace(element, true);
}

This will only update existing keys with matching elements in list.

As a side note, a Map<K, Boolean> can often be replaced by a lighter Set<K>.

Upvotes: 2

RP-
RP-

Reputation: 5837

You don't need to iterate HashMap explicitly. hashMap.containsKey(key) checks if a key present in the map or not in an optimized way. You need to study a bit on how HashMap works.

Iterate List:
    if HashMap.containsKey(List[i])
        HashMap.put(List[i], true)

This will work.

Upvotes: 3

Related Questions