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
102
votes
3 answers

Is gcc std::unordered_map implementation slow? If so - why?

We are developing a highly performance critical software in C++. There we need a concurrent hash map and implemented one. So we wrote a benchmark to figure out, how much slower our concurrent hash map is compared with std::unordered_map. But,…
Markus Pilman
  • 3,104
  • 3
  • 22
  • 31
101
votes
7 answers

Working with dictionaries/lists to get list of keys

I have trivial question: I couldn't find a dictionary data structure in R, so I used list instead (like "word"->number). So, how do I get the list of keys.
Ivri
  • 2,159
  • 5
  • 25
  • 33
99
votes
10 answers

Super high performance C/C++ hash map (table, dictionary)

I need to map primitive keys (int, maybe long) to struct values in a high-performance hash map data structure. My program will have a few hundred of these maps, and each map will generally have at most a few thousand entries. However, the maps will…
Haywood Jablomey
  • 1,011
  • 1
  • 8
  • 4
98
votes
5 answers

What is the optimal capacity and load factor for a fixed-size HashMap?

I'm trying to figure out the optimal capacity and load factor for a specific case. I think I got the gist of it, but I'd still be thankful for a confirmation from someone more knowledgable than me. :) If I know that my HashMap will fill up to…
Domchi
  • 10,705
  • 6
  • 54
  • 64
98
votes
6 answers

Is there Java HashMap equivalent in PHP?

I need PHP object similar to HashMap in Java, but I didn't find when I googled, so if someone knows how I can mimic HashMaps in PHP, help would be appreciated.
newbie
  • 24,286
  • 80
  • 201
  • 301
95
votes
4 answers

When to use HashMap over LinkedList or ArrayList and vice-versa

What is the reason why we cannot always use a HashMap, even though it is much more efficient than ArrayList or LinkedList in add,remove operations, also irrespective of the number of the elements. I googled it and found some reasons, but there was…
user517491
94
votes
2 answers

How to check if a map is empty in Golang?

When the following code: m := make(map[string]string) if m == nil { log.Fatal("map is empty") } is run, the log statement is not executed, while fmt.Println(m) indicates that the map is empty: map[]
030
  • 10,842
  • 12
  • 78
  • 123
94
votes
2 answers

ConcurrentHashMap and Hashtable in Java

What is the difference between a ConcurrentHashMap and a Hashtable in Java? Which is more efficient for threaded applications?
sheidaei
  • 9,842
  • 20
  • 63
  • 86
93
votes
12 answers

Reverse HashMap keys and values in Java

It's a simple question, I have a simple HashMap of which i want to reverse the keys and values. HashMap myHashMap = new HashMap(); myHashMap.put('a', "test one"); myHashMap.put('b', "test two"); and I want to…
Ken
  • 2,859
  • 4
  • 24
  • 26
93
votes
9 answers

Collision resolution in Java HashMap

Java HashMap uses put method to insert the K/V pair in HashMap. Lets say I have used put method and now HashMap has one entry with key as 10 and value as 17. If I insert 10,20 in this HashMap it simply replaces the the previous…
user2938723
  • 1,100
  • 1
  • 10
  • 15
92
votes
9 answers

Sorting hashmap based on keys

I have the following hashmap in java: {B046=0.0, A061=3.0, A071=0.0, B085=0.0, B075=3.0, B076=9.0, B086=3.0, B095=0.0, B096=0.0, A052=0.0, B066=0.0, B056=9.0, B065=0.0, B055=9.0} How should I go about sorting the hashmap such that the Alphabet,…
user1008697
  • 1,141
  • 2
  • 10
  • 13
92
votes
8 answers

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

I need to copy all keys and values from one A HashMap onto another one B, but not to replace existing keys and values. Whats the best way to do that? I was thinking instead iterating the keySet and checkig if it exist or not, I would Map temp = new…
rapadura
  • 5,242
  • 7
  • 39
  • 57
91
votes
5 answers

How do I create some variable type alias in Java

let say I have this code Map list = new HashMap(); list.put("number1", "one"); list.put("number2", "two"); how can I make some "alias" the type Map to something that easier to be rewritten like //…
Lee
  • 3,259
  • 4
  • 21
  • 27
91
votes
7 answers

What is the use of adding a null key or value to a HashMap in Java?

HashMap allows one null key and any number of null values. What is the use of it?
subhashis
  • 4,629
  • 8
  • 37
  • 52
90
votes
9 answers

Shortcut for adding to List in a HashMap

I often have a need to take a list of objects and group them into a Map based on a value contained in the object. Eg. take a list of Users and group by Country. My code for this usually looks like: Map> usersByCountry = new…
Damo
  • 11,410
  • 5
  • 57
  • 74