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?
It is a non-synchronized class of Java collection. Whereas the LinkedHashMap is an alternative to HashMap that has the support of maintaining the order of the elements. The LinkedHashMap inherits the HashMap class and implements the Map interface of the Java Collection frameworks.
The replace(K key, V value) method of Map interface, implemented by HashMap class is used to replace the value of the specified key only if the key is previously mapped with some value. Parameters: This method accepts two parameters: key: which is the key of the element whose value has to be replaced.
Use wrappers for composite HashMap keys Whenever a HashMap has composite String keys, use a wrapper instead of concatenating the strings to make a key. Doing so will make the lookup much faster and reduce allocation rate, as the benchmark below demonstrates.
Modern Java's HashMap is a powerful and well-optimized data structure. Its performance can, however, be worsened by a badly designed hashCode method. In this tutorial, we looked at possible ways to make hashing fast and effective. As always, the code examples for this article are available over on GitHub.
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 introduced a new method replaceAll()
for just such a purpose, making the code required even simpler:
selectedIds.replaceAll((k, v) -> true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With