Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 906
user1285928 Avatar asked May 24 '12 14:05

user1285928


People also ask

What can we use instead of HashMap in Java?

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.

Can we replace value in HashMap?

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.

How can HashMap be made more efficient?

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.

Is HashMap is efficient in Java?

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.


1 Answers

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);
like image 179
Bohemian Avatar answered Oct 17 '22 19:10

Bohemian