0

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.

3
  • 2
    You don't need to Iterate HashMap:. Commented Aug 6, 2017 at 23:23
  • Why iterate the map? Just iterate the list and use it's value as key to set the value to true. for (Object k : list) map.put(k, true) Commented Aug 6, 2017 at 23:25
  • This sounds more like a set than a map. You could just build a Set from the ArrayList's contents; then anything that's not in the set is false. Two reasons to keep the Map instead: 1. Some other interface requires a Map; 2. You need to throw an exception for unexpected keys like "KMFDM" instead of just returning false. Commented Aug 7, 2017 at 0:44

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

No, there are no stupid questions :) just a matter of time to learn.
2

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>.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.