6

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?

mtk
  • 13,221
  • 16
  • 72
  • 112
user1285928
  • 1,328
  • 29
  • 98
  • 147

2 Answers2

11

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);
Community
  • 1
  • 1
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 3
    Why is grabbing the entire entry faster than just the key? Does setValue have less overhead? – David B May 24 '12 at 14:22
  • 3
    @DavidB Because with `setValue()` there is no key lookup. Your solution must lookup every key, because it uses `put()` n times! This solutions looks up nothing - it directly sets the value of every entry. I encourage you to learn this way of iterating over a map - it should always be used in preference to iterating over the key set using lookups - both `get()` or `put()` look up the key, which requires hash code comparisons and algorithms (which are fast sure, but it's still work) – Bohemian May 24 '12 at 14:26
5

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);
 }
David B
  • 2,688
  • 18
  • 25
  • 1
    No problem. If it helps (after the 15 minute wait period), click the green checkmark to the accept the answer. :) – David B May 24 '12 at 14:17
  • 2
    Don't you need `selectedIds.keySet()` ? Or is that automatic? – tskuzzy May 24 '12 at 14:17
  • @tskuzzy [You're right, I do.](http://stackoverflow.com/a/1066607/451590). Thank you! :) – David B May 24 '12 at 14:19
  • 1
    This is **NOT** the fastest way, because an unnecessary lookup must occur for *every* entry. See my answer for the fastest way. – Bohemian May 24 '12 at 14:20