Questions tagged [hashmap]

A data structure that uses a hash function to map identifying values, known as keys, to their associated values

A hash map (or hash table) is a data structure which contains "key-value" pairs and allows retrieving values by key.

The most attractive feature is fast lookup of elements, particularly for large numbers of elements. Hash maps work by using a hash function to transform keys into a hash number that is then used as an index into an array of "buckets" containing one or more elements. This allows constant time access to the relevant bucket, followed by a linear search for the desired element within the bucket. When the number of elements in each bucket is kept low (possibly by dynamically resizing the array of buckets as elements are inserted) this offers constant time lookup on average even when the number of elements in the hash map increases. This can be a significant advantage compared to lookup in a tree-based structures which needs to perform more steps as the number of elements increases.

A drawback of hash tables is that elements are not stored in an obvious or meaningful order, as a good hash function will not map neighbouring keys to neighbouring buckets.

If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table.

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

Map m = Collections.synchronizedMap(new HashMap(...));

The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

Official docs: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

Stackoverflow Link: Differences between HashMap and Hashtable?

15203 questions
216
votes
11 answers

HashMap - getting First Key value

Below are the values contain in the HashMap statusName {Active=33, Renewals Completed=3, Application=15} Java code to getting the first Key (i.e Active) Object myKey = statusName.keySet().toArray()[0]; How can we collect the first Key "Value" (i.e…
Prabu
  • 3,550
  • 9
  • 44
  • 85
213
votes
20 answers

Difference between HashSet and HashMap?

Apart from the fact that HashSet does not allow duplicate values, what is the difference between HashMap and HashSet? I mean implementation wise? It's a little bit vague because both use hash tables to store values.
SpikETidE
  • 6,711
  • 15
  • 46
  • 62
212
votes
9 answers

Array to Hash Ruby

Convert this Array: a = ["item 1", "item 2", "item 3", "item 4"] ...to a Hash: { "item 1" => "item 2", "item 3" => "item 4" } i.e. elements at even indexes are keys and odd ones are values.
djhworld
  • 6,726
  • 4
  • 30
  • 44
199
votes
7 answers

SparseArray vs HashMap

I can think of several reasons why HashMaps with integer keys are much better than SparseArrays: The Android documentation for a SparseArray says "It is generally slower than a traditional HashMap". If you write code using HashMaps rather than…
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
198
votes
6 answers

How to create a simple map using JavaScript/JQuery

How can you create the JavaScript/JQuery equivalent of this Java code: Map map = new HashMap(); //Doesn't not have to be a hash map, any key/value map is fine map.put(myKey1, myObj1); map.put(myKey2, myObj2); //Repeat n times function Object get(k)…
Marcus Leon
  • 55,199
  • 118
  • 297
  • 429
192
votes
16 answers

HashMap to return default value for non-found keys?

Is it possible to have a HashMap return a default value for all keys that are not found in the set?
Larry
  • 11,439
  • 15
  • 61
  • 84
188
votes
8 answers

HashMap get/put complexity

We are used to saying that HashMap get/put operations are O(1). However it depends on the hash implementation. The default object hash is actually the internal address in the JVM heap. Are we sure it is good enough to claim that the get/put are…
Michael
  • 41,026
  • 70
  • 193
  • 341
188
votes
15 answers

Is a Java hashmap search really O(1)?

I've seen some interesting claims on SO re Java hashmaps and their O(1) lookup time. Can someone explain why this is so? Unless these hashmaps are vastly different from any of the hashing algorithms I was bought up on, there must always exist a…
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
187
votes
2 answers

How to lookup from and insert into a HashMap efficiently?

I'd like to do the following: Lookup a Vec for a certain key, and store it for later use. If it doesn't exist, create an empty Vec for the key, but still keep it in the variable. How to do this efficiently? Naturally I thought I could use…
Yusuke Shinyama
  • 1,873
  • 2
  • 11
  • 5
184
votes
20 answers

Finding Key associated with max Value in a Java Map

What is the easiest way to get key associated with the max value in a map? I believe that Collections.max(someMap) will return the max Key, when you want the key that corresponds to the max value.
Ben B.
  • 3,706
  • 5
  • 26
  • 27
178
votes
6 answers

How to swap keys and values in a hash

How do I swap keys and values in a Hash? I have the following Hash: {:a=>:one, :b=>:two, :c=>:three} that I want to transform into: {:one=>:a, :two=>:b, :three=>:c} Using map seems rather tedious. Is there a shorter solution?
Jonathan Allard
  • 18,429
  • 11
  • 54
  • 75
176
votes
11 answers

adding multiple entries to a HashMap at once in one statement

I need to initialize a constant HashMap and would like to do it in one line statement. Avoiding sth like this: hashMap.put("One", new Integer(1)); // adding value into HashMap hashMap.put("Two", new Integer(2)); hashMap.put("Three", new…
user387184
  • 10,953
  • 12
  • 77
  • 147
174
votes
4 answers

Why use symbols as hash keys in Ruby?

A lot of times people use symbols as keys in a Ruby hash. What's the advantage over using a string? E.g.: hash[:name] vs. hash['name']
user979912
169
votes
12 answers

Is it safe to get values from a java.util.HashMap from multiple threads (no modification)?

There is a case where a map will be constructed, and once it is initialized, it will never be modified again. It will however, be accessed (via get(key) only) from multiple threads. Is it safe to use a java.util.HashMap in this way? (Currently,…
Dave L.
  • 43,907
  • 11
  • 63
  • 62
167
votes
4 answers

How can I update a value in a mutable HashMap?

Here is what I am trying to do: use std::collections::HashMap; fn main() { let mut my_map = HashMap::new(); my_map.insert("a", 1); my_map.insert("b", 3); my_map["a"] += 10; // I expect my_map becomes {"b": 3, "a": 11} } But…
Akavall
  • 82,592
  • 51
  • 207
  • 251