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?

13758 questions
3964
votes
36 answers

What are the differences between a HashMap and a Hashtable in Java?

What are the differences between a HashMap and a Hashtable in Java? Which is more efficient for non-threaded applications?
dmanxiii
  • 47,479
  • 10
  • 30
  • 23
3532
votes
7 answers

Iterate through a HashMap

What's the best way to iterate over the items in a HashMap?
burntsugar
  • 54,120
  • 21
  • 51
  • 77
679
votes
17 answers

How to update a value, given a key in a hashmap?

Suppose we have a HashMap in Java. How do I update (increment) the integer-value of the string-key for each existence of the string I find? One could remove and reenter the pair, but overhead would be a concern. Another way would be…
laertis
  • 7,119
  • 3
  • 17
  • 17
604
votes
9 answers

Why there is no ConcurrentHashSet against ConcurrentHashMap

HashSet is based on HashMap. If we look at HashSet implementation, everything is been managed under HashMap. is used as a key of HashMap. And we know that HashMap is not thread safe. That is why we have ConcurrentHashMap in…
Talha Ahmed Khan
  • 13,774
  • 10
  • 39
  • 47
602
votes
16 answers

How to remove a key from Hash and get the remaining hash in Ruby/Rails?

To add a new pair to Hash I do: {:a => 1, :b => 2}.merge!({:c => 3}) #=> {:a => 1, :b => 2, :c => 3} Is there a similar way to delete a key from Hash ? This works: {:a => 1, :b => 2}.reject! { |k| k == :a } #=> {:b => 2} but I would expect to…
Misha Moroshko
  • 148,413
  • 200
  • 467
  • 700
520
votes
2 answers

How to preserve insertion order in HashMap?

I'm using a HashMap. When I iterate over the map, the data is returned in (often the same) random order. But the data was inserted in a specific order, and I need to preserve the insertion order. How can I do this?
realtebo
  • 19,593
  • 31
  • 85
  • 151
477
votes
36 answers

Java Hashmap: How to get key from value?

If I have the value "foo", and a HashMap ftw for which ftw.containsValue("foo") returns true, how can I get the corresponding key? Do I have to loop through the hashmap? What is the best way to do that?
Nick Heiner
  • 108,809
  • 177
  • 454
  • 689
398
votes
17 answers

How to sort Map values by key in Java?

I have a Map that has strings for both keys and values. Data is like following: "question1", "1" "question9", "1" "question2", "4" "question5", "2" I want to sort the map based on its keys. So, in the end, I will have question1,…
n00bstackie
  • 4,233
  • 4
  • 17
  • 9
398
votes
16 answers

Convert object array to hash map, indexed by an attribute value of the Object

Use Case The use case is to convert an array of objects into a hash map based on string or function provided to evaluate and use as the key in the hash map and value as an object itself. A common case of using this is converting an array of objects…
Naveen I
  • 4,277
  • 2
  • 13
  • 8
373
votes
13 answers

What is the difference between the HashMap and Map objects in Java?

What is the difference between the following maps I create (in another question, people answered using them seemingly interchangeably and I'm wondering if/how they are different): HashMap map = new HashMap
Tony Stark
  • 21,996
  • 37
  • 90
  • 111
372
votes
17 answers

JavaScript hashmap equivalent

As made clear in update 3 on this answer, this notation: var hash = {}; hash[X] does not actually hash the object X; it actually just converts X to a string (via .toString() if it's an object, or some other built-in conversions for various…
Claudiu
  • 206,738
  • 150
  • 445
  • 651
362
votes
5 answers

How to convert a ruby hash object to JSON?

How to convert a ruby hash object to JSON? So I am trying this example below & it doesn't work? I was looking at the RubyDoc and obviously Hash object doesn't have a to_json method. But I am reading on blogs that Rails supports active_record.to_json…
kapso
  • 10,921
  • 14
  • 53
  • 72
355
votes
7 answers

C# Java HashMap equivalent

Coming from a Java world into a C# one is there a HashMap equivalent? If not what would you recommend?
John
  • 3,847
  • 3
  • 18
  • 14
328
votes
10 answers

Key existence check in HashMap

Is checking for key existence in HashMap always necessary? I have a HashMap with say a 1000 entries and I am looking at improving the efficiency. If the HashMap is being accessed very frequently, then checking for the key existence at every access…
athena
  • 5,079
  • 8
  • 26
  • 30
319
votes
16 answers

java.lang.OutOfMemoryError: GC overhead limit exceeded

I am getting this error in a program that creates several (hundreds of thousands) HashMap objects with a few (15-20) text entries each. These Strings have all to be collected (without breaking up into smaller amounts) before being submitted to a…
PNS
  • 17,431
  • 26
  • 86
  • 131
1
2 3
99 100