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
128
votes
7 answers

Why does Map.of not allow null keys and values?

With Java 9, new factory methods have been introduced for the List, Set and Map interfaces. These methods allow quickly instantiating a Map object with values in one line. Now, if we consider: Map map1 = new HashMap
hi.nitish
  • 2,732
  • 2
  • 14
  • 21
127
votes
17 answers

How to sort a HashMap in Java

How are we able to sort a HashMap? I want to sort on the basis of a value in the ArrayList.
rosh
124
votes
6 answers

map vs. hash_map in C++

I have a question with hash_map and map in C++. I understand that map is in STL, but hash_map is not a standard. What's the difference between the two?
skydoor
  • 25,218
  • 52
  • 147
  • 201
124
votes
13 answers

HashMap and int as key

I am trying to build a HashMap which will have integer as keys and objects as values. My syntax is: HashMap myMap = new HashMap(); However, the error returned is - Syntax error on token "int", Dimensions expected after…
MrD
  • 4,986
  • 11
  • 48
  • 90
119
votes
7 answers

How is a JavaScript hash map implemented?

I currently work with OpenLayers and have a huge set of data to draw into a vector layer (greater than 100000 vectors). I'm now trying to put all these vectors into a JavaScript hash map to analyze the performance. I want to know how is the hash…
Patrick Hillert
  • 2,309
  • 4
  • 22
  • 37
118
votes
9 answers

Is it possible to rename a Hashmap key?

I'm looking for a way to rename a Hashmap key, but i don't know if it's possible in Java.
Ikes
  • 1,520
  • 3
  • 10
  • 8
117
votes
14 answers

Is it possible to get element from HashMap by its position?

How to retrieve an element from HashMap by its position, is it possible at all?
Eugene
  • 59,186
  • 91
  • 226
  • 333
117
votes
11 answers

Java Compare Two Lists

I have two lists ( not java lists, you can say two columns) For example **List 1** **Lists 2** milan hafil dingo iga iga dingo elpha binga hafil …
user238384
  • 2,396
  • 10
  • 35
  • 36
114
votes
6 answers

HashMap Java 8 implementation

As per the following link document: Java HashMap Implementation I'm confused with the implementation of HashMap (or rather, an enhancement in HashMap). My queries are: Firstly static final int TREEIFY_THRESHOLD = 8; static final int…
Hasnain Ali Bohra
  • 2,130
  • 2
  • 11
  • 25
109
votes
25 answers

Java HashMap performance optimization / alternative

I want to create a large HashMap but the put() performance is not good enough. Any ideas? Other data structure suggestions are welcome but I need the lookup feature of a Java Map: map.get(key) In my case I want to create a map with 26 million…
nash
  • 3,020
  • 6
  • 38
  • 53
108
votes
6 answers

Collect values in order, each containing a map

When iterating through the returned map in the code, returned by the topic function, the keys are not appearing in order. How can I get the keys to be in order / sort the map so that the keys are in order and the values correspond? Here is the code.
gramme.ninja
  • 1,341
  • 3
  • 11
  • 11
107
votes
8 answers

How safe are Golang maps for concurrent Read/Write operations?

According to the Go blog, Maps are not safe for concurrent use: it's not defined what happens when you read and write to them simultaneously. If you need to read from and write to a map from concurrently executing goroutines, the accesses must be…
John D.
  • 1,569
  • 2
  • 13
  • 11
104
votes
1 answer

How std::unordered_map is implemented

c++ unordered_map collision handling , resize and rehash This is a previous question opened by me and I have seen that I am having a lot of confusion about how unordered_map is implemented. I am sure many other people shares that confusion with me.…
ralzaul
  • 4,280
  • 6
  • 32
  • 51
104
votes
4 answers

Is a HashMap thread-safe for different keys?

If I have two multiple threads accessing a HashMap, but guarantee that they'll never be accessing the same key at the same time, could that still lead to a race condition?
agentofuser
  • 8,987
  • 11
  • 54
  • 85
103
votes
7 answers

Does Java have a HashMap with reverse lookup?

I have data that is organized in kind of a "key-key" format, rather than "key-value". It's like a HashMap, but I will need O(1) lookup in both directions. Is there a name for this type of data structure, and is anything like this included in…
Kip
  • 107,154
  • 87
  • 232
  • 265