user1285928
user1285928

Reputation: 1476

How to effectively replace Java HashMap with boolean values

I'm interested how I can very quickly change the Boolean values into this hashmap:

HashMap<String, Boolean> selectedIds = new HashMap<>(); 

I want very quickly to replace the Boolean values all to be true. How I can do this?

Upvotes: 6

Views: 5441

Answers (2)

Bohemian
Bohemian

Reputation: 425358

The fastest way is this:

for (Map.Entry<String, Boolean> entry : selectedIds.entrySet()) {
    entry.setValue(true);
}

This code avoids any lookups whatsoever, because it iterates though the entire map's entries and sets their values directly.

Note that whenever HashMap.put() is called, a key look up occurs in the internal Hashtable. While the code is highly optimized, it nevertheless requires work to calculate and compare hashcodes, then employ an algorithm to ultimately find the entry (if it exists). This is all "work", and consumes CPU cycles.


Java 8 update:

Java 8 introduced a new method replaceAll() for just such a purpose, making the code required even simpler:

selectedIds.replaceAll((k, v) -> true);

Upvotes: 11

David B
David B

Reputation: 2698

This will iterate through your map and replace all the old values with a true value for each key. HashMap put method

for(String s : selectedIds.keySet()) {
    selectedIds.put(s, true);
 }

Upvotes: 5

Related Questions