How to effectively replace Java HashMap with boolean values

hashmap, initialization, java

Solution

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);

Problem

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?

Original source

Related problems