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

is the Java HashMap keySet() iteration order consistent?

I understand that the Set returned from a Map's keySet() method does not guarantee any particular order. My question is, does it guarantee the same order over multiple iterations. For example Map map = getMap(); for( K k : map.keySet()…
karoberts
  • 9,828
  • 4
  • 39
  • 39
90
votes
10 answers

why HashMap Values are not cast in List?

I'm putting values into the hashmap which is of the form, Map highLowValueMap=new HashMap(); highLowValueMap.put(1l, 10.0); highLowValueMap.put(2l, 20.0); I want to create a list by using values() method of…
bNd
  • 7,512
  • 7
  • 39
  • 72
90
votes
9 answers

Ruby - mapping an array to hashmap

I have an array, and a function that returns a value given a value. Ultimately I want to create a hashmap that has the values of the array as key value, and the result of f(key_value) as the value. Is there a clean, simple way, like similar to…
Ji Mun
  • 1,800
  • 4
  • 18
  • 27
89
votes
2 answers

How to send hashmap value to another activity using an intent

How to send HashMap value from one Intent to second Intent? Also, how to retrieve that HashMap value in the second Activity?
Piyush
  • 3,061
  • 8
  • 34
  • 52
88
votes
2 answers

Does "put" overwrite existing values?

New to hashtables with a simple question. For some reason googling hasn't gotten me a straight answer. Say I've got an hashtable set up: myHashtable.put(1,"bird"); myHashtable.put(2,"iguana"); and I want to change "bird" to "fish"…
Ben
  • 54,723
  • 49
  • 178
  • 224
87
votes
9 answers

Android - Get value from HashMap

I have tried to search on HashMap in Android, but getting problem: Consider this example: HashMap meMap=new HashMap
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
86
votes
8 answers

C# equivalent of C++ map

I want to keep some totals for different accounts. In C++ I'd use STL like this: map accounts; // Add some amounts to some accounts. accounts["Fred"] += 4.56; accounts["George"] += 1.00; accounts["Fred"] += 1.00; cout << "Fred owes…
Adam Pierce
  • 33,531
  • 22
  • 69
  • 89
84
votes
4 answers

Idiomatic way to transform map in kotlin?

In Scala, it's just the map function. For example, if hashMap is a hashMap of strings, then you can do the following: val result : HashMap[String,String] = hashMap.map(case(k,v) => (k -> v.toUpperCase)) In Kotlin, however, map turns the map into a…
U Avalos
  • 6,538
  • 7
  • 48
  • 81
84
votes
4 answers

Is there a more concise or declarative way to initialize a HashMap?

I'm using a HashMap to count the occurrences of different characters in a string: let text = "GATTACA"; let mut counts: HashMap = HashMap::new(); counts.insert('A', 0); counts.insert('C', 0); counts.insert('G', 0); counts.insert('T',…
anderspitman
  • 9,230
  • 10
  • 40
  • 61
84
votes
8 answers

Performance ConcurrentHashmap vs HashMap

How is the performance of ConcurrentHashMap compared to HashMap, especially .get() operation (I'm especially interested for the case of only few items, in the range between maybe 0-5000)? Is there any reason not to use ConcurrentHashMap instead of…
Mauli
  • 16,863
  • 27
  • 87
  • 114
82
votes
7 answers

Hashmap does not work with int, char

Possible Duplicate: Storing primitive values in a Java collection? In java when I use the following :- public HashMap buildMap(String letters) { HashMap checkSum = new HashMap(); for ( int i = 0; i <…
user277465
82
votes
13 answers

Using a byte array as Map key

Do you see any problem with using a byte array as Map key? I could also do new String(byte[]) and hash by String but it is more straightforward to use byte[].
shikhar
  • 2,432
  • 1
  • 19
  • 14
81
votes
5 answers

Python dictionary keys. "In" complexity

Quick question to mainly satisfy my curiosity on the topic. I am writing some large python programs with an SQlite database backend and will be dealing with a large number of records in the future, so I need to optimize as much as I can. For a few…
tknickman
  • 4,285
  • 3
  • 34
  • 47
80
votes
7 answers

HashMaps and Null values?

How do you pass in null values into a HashMap? The following code snippet works with options filled in: HashMap options = new HashMap(); options.put("name", "value"); Person person = sample.searchPerson(options); …
Neutron_boy
  • 919
  • 1
  • 6
  • 7
79
votes
6 answers

How to return a list of keys from a Hash Map?

I'm currently trying to make a program that conjugates verbs into Spanish. I've created a Hash Table that contains a key and an instantiation of the object Verb. The key is a string that has the infinitive form of the verb (for example, "hablar").…
idungotnosn
  • 2,001
  • 4
  • 29
  • 36