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
164
votes
12 answers

Sorting HashMap by values

I need to sort my HashMap according to the values stored in it. The HashMap contains the contacts name stored in phone. Also I need that the keys get automatically sorted as soon as I sort the values, or you can say the keys and values are bound…
prof_jack
  • 2,023
  • 3
  • 18
  • 19
162
votes
9 answers

How do I create a HashMap literal?

How I can create a HashMap literal in Rust? In Python I can do it so: hashmap = { 'element0': { 'name': 'My New Element', 'childs': { 'child0': { 'name': 'Child For Element 0', 'childs': { …
Maxim Samburskiy
  • 1,811
  • 2
  • 11
  • 13
159
votes
6 answers

How to understand Locality Sensitive Hashing?

I noticed that LSH seems a good way to find similar items with high-dimension properties. After reading the paper http://www.slaney.org/malcolm/yahoo/Slaney2008-LSHTutorial.pdf, I'm still confused with those formulas. Does anyone know a blog or…
WoooHaaaa
  • 19,732
  • 32
  • 90
  • 138
158
votes
9 answers

Does adding a duplicate value to a HashSet/HashMap replace the previous value

Please consider the below piece of code: HashSet hs = new HashSet(); hs.add("hi"); -- (1) hs.add("hi"); -- (2) hs.size() will give 1 as HashSet doesn't allow duplicates so only one element will be stored. I want to know if we add the duplicate…
Anand
  • 20,708
  • 48
  • 131
  • 198
155
votes
8 answers

Best way to create an empty map in Java

I need to create an empty map. if (fileParameters == null) fileParameters = (HashMap) Collections.EMPTY_MAP; The problem is that the above code produces this warning: Type safety: Unchecked cast from Map to HashMap What is the…
JorgeO
  • 2,210
  • 5
  • 20
  • 22
154
votes
5 answers

How to convert JSON to a Ruby hash

I have a JSON object holding the following value: @value = {"val":"test","val1":"test1","val2":"test2"} I want to loop through it in Ruby to get the key/value pairs. When I use @each, it doesn't iterate through the object because it is not in the…
verdure
  • 3,201
  • 6
  • 26
  • 27
154
votes
3 answers

How to loop through a HashMap in JSP?

How can I loop through a HashMap in JSP? <% HashMap countries = MainUtils.getCountries(l); %>
blub
  • 1,541
  • 2
  • 10
  • 3
153
votes
20 answers

Ruby convert Object to Hash

Let's say I have a Gift object with @name = "book" & @price = 15.95. What's the best way to convert that to the Hash {name: "book", price: 15.95} in Ruby, not Rails (although feel free to give the Rails answer too)?
ma11hew28
  • 121,420
  • 116
  • 450
  • 651
144
votes
6 answers

Which Java Collection should I use?

In this question How can I efficiently select a Standard Library container in C++11? is a handy flow chart to use when choosing C++ collections. I thought that this was a useful resource for people who are not sure which collection they should be…
Tim B
  • 40,716
  • 16
  • 83
  • 128
142
votes
11 answers

Copying a HashMap in Java

I am trying to keep a temporary container of a class that contains member : HashMap myobjectHashMap A class called myobjectsList Then I do myobjectsListA = new myobjectsList(); myobjectsListB = new myobjectsList(); then: Add some…
user691305
  • 1,560
  • 2
  • 9
  • 12
137
votes
12 answers

What is the best way to convert an array to a hash in Ruby

In Ruby, given an array in one of the following forms... [apple, 1, banana, 2] [[apple, 1], [banana, 2]] ...what is the best way to convert this into a hash in the form of... {apple => 1, banana => 2}
Nathan Fritz
  • 2,268
  • 3
  • 20
  • 14
137
votes
14 answers

How to create a HashMap with two keys (Key-Pair, Value)?

I have a 2D array of Integers. I want them to be put into a HashMap. But I want to access the elements from the HashMap based on Array Index. Something like: For A[2][5], map.get(2,5) which returns a value associated with that key. But how do I…
Crocode
  • 3,056
  • 6
  • 26
  • 31
136
votes
7 answers

Remove Elements from a HashSet while Iterating

So, if I try to remove elements from a Java HashSet while iterating, I get a ConcurrentModificationException. What is the best way to remove a subset of the elements from a HashSet as in the following example? Set set = new…
Scott
136
votes
14 answers

Java: how to convert HashMap to array

I need to convert a HashMap to an array; could anyone show me how it's done?
burntsugar
  • 57,360
  • 21
  • 58
  • 81
131
votes
10 answers

get string value from HashMap depending on key name

I have a HashMap with various keys and values, how can I get one value out? I have a key in the map called my_code, it should contain a string, how can I just get that without having to iterate through the map? So far I've got.. HashMap newMap =…
Jimmy
  • 16,123
  • 39
  • 133
  • 213