How to effectively replace Java HashMap with booleans

I am wondering how I can very quickly change the boolean values ​​to this hash map:

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

I want to quickly replace booleans so that everyone is true. How can i do this?

+4
source share
2 answers

The fastest way:

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

This code avoids any lookups because it iterates through all the map entries and sets their values ​​directly.

Note that whenever HashMap.put() is HashMap.put() , a key search appears in the internal Hashtable . Although the code is highly optimized, it nevertheless requires work to calculate and compare hash codes, and then uses the algorithm to finally search for the record (if it exists). It all "works" and consumes CPU cycles.


Java 8 update:

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

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

This will lead to going through your map and replacing all old values ​​with the true value for each key. HashMap placement method

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

Source: https://habr.com/ru/post/1414153/


All Articles