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
51
votes
6 answers

Key existence checking utility in Map

I'm using the following code for checking if a key exists in a Map instance: if (!map_instance.containsKey(key)) throw new RuntimeException("Specified key doesn't exist in map"); else return map_instance.get(key); My question is: Is there a…
Sam
  • 6,770
  • 7
  • 50
  • 91
50
votes
8 answers

How is the implementation of LinkedHashMap different from HashMap?

If LinkedHashMap's time complexity is same as HashMap's complexity why do we need HashMap? What are all the extra overhead LinkedHashMap has when compared to HashMap in Java?
Passionate programmer
  • 5,748
  • 10
  • 39
  • 43
50
votes
10 answers

Java - get index of key in HashMap?

In java if I am looping over the keySet() of a HashMap, how do I (inside the loop), get the numerical index of that key? Basically, as I loop through the map, I want to be able to get 0,1,2...I figure this would be cleaner than declaring an int and…
llm
  • 5,539
  • 12
  • 36
  • 30
50
votes
3 answers

collecting HashMap> java 8

I want to be able to convert a List to a HashMap where the key is the elementName and the values is a list of something random (in this case its the Element Name). So in short I want (A->List(A), B->List(B), C-> List(C)). I tried using toMap() and…
user3869813
  • 749
  • 1
  • 7
  • 12
50
votes
1 answer

Difference between hash_map and unordered_map?

I recently discovered that the implementation of the hash map in C++ will be called unordered_map. When I looked up why they weren't just using hash_map, I discovered that apparently there are compatibility issues with the implementation of hash_map…
kidnamedlox
  • 806
  • 1
  • 7
  • 14
49
votes
5 answers

Android - How to pass HashMap between activities?

How to pass the detail HashMap to another Activity? HashMap detail = new HashMap(); detail.add("name","paresh"); detail.add("surname","mayani"); detail.add("phone","99999"); ...... ......
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
49
votes
2 answers

Collect stream into a HashMap with Lambda in Java 8

I have a HashMap which I need to filter using some function: HashMap, Double> container Map.Entry, Double> map = container.entrySet() .stream() .filter(k -> k.getKey().size() == size) For the size =…
chao
  • 1,893
  • 2
  • 23
  • 27
49
votes
11 answers

How do I access nested HashMaps in Java?

I have a HashMap in Java, the contents of which (as you all probably know) can be accessed by HashMap.get("keyname"); If a have a HashMap inside another HashMap i.e. a nested HashMap, how would i access the contents? Can i do this like this,…
Mridang Agarwalla
  • 43,201
  • 71
  • 221
  • 382
49
votes
3 answers

Set Key and Value in spinner

I have a spiner and I want set a key and a value on this,I use of HashMap,It's work,but show one row,like this: Code: final View rootView = inflater.inflate(R.layout.fragment_photos, container, false); Spinner…
Nima.S-H
  • 777
  • 1
  • 9
  • 19
48
votes
6 answers

How can I have a HashMap with unique keys in java?

How can I have a HashMap with unique keys in Java? Or even does this make any sense to have unique keys in HashMap or the keys are unique by default? I am a newbie. thx
Hossein
  • 40,161
  • 57
  • 141
  • 175
48
votes
6 answers

Ruby value of a hash key?

I've got a list of values that are in a Ruby hash. Is there a way to check the value of the key and if it equals "X", then do "Y"? I can test to see if the hash has a key using hash.has_key?, but now I need to know if hash.key == "X" then...?
cswebgrl
  • 687
  • 1
  • 7
  • 11
48
votes
3 answers

How to implement HashMap with two keys?

HashMap implements the get and insert methods which take a single immutable borrow and a single move of a value respectively. I want a trait which is just like this but which takes two keys instead of one. It uses the map inside, but it's just a…
lsunsi
  • 505
  • 4
  • 7
48
votes
4 answers

Is Java HashMap.clear() and remove() memory effective?

Consider the follwing HashMap.clear() code: /** * Removes all of the mappings from this map. * The map will be empty after this call returns. */ public void clear() { modCount++; Entry[] tab = table; for (int i = 0; i < tab.length;…
Illarion Kovalchuk
  • 5,774
  • 8
  • 42
  • 54
47
votes
7 answers

Why does HashSet implementation in Sun Java use HashMap as its backing?

Looking at the source of Java 6, HashSet is actually implemented using HashMap, using dummy object instance on every entry of the Set. I think that wastes 4 byte (on 32-bit machines) for the size of the entry itself. But, why is it…
Randy Sugianto 'Yuku'
  • 71,383
  • 57
  • 178
  • 228
47
votes
4 answers

Converting Map to Map

I have Two Maps Map filterMap Map filterMapObj What I need is I would like to convert that Map to Map. Here I am using the code if (filterMap != null) { for…
arjuncc
  • 3,227
  • 5
  • 42
  • 77