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
79
votes
17 answers

Which is faster, Hash lookup or Binary search?

When given a static set of objects (static in the sense that once loaded it seldom if ever changes) into which repeated concurrent lookups are needed with optimal performance, which is better, a HashMap or an array with a binary search using some…
TheSoftwareJedi
  • 34,421
  • 21
  • 109
  • 151
77
votes
3 answers

How to iterate through a Hashmap, print the key/value and remove the value in Rust?

This should be a trivial task in any language. This isn't working in Rust. use std::collections::HashMap; fn do_it(map: &mut HashMap) { for (key, value) in map { println!("{} / {}", key, value); …
adapt-dev
  • 1,608
  • 1
  • 19
  • 30
77
votes
8 answers

Hashmap with Streams in Java 8 Streams to collect value of Map

Let consider a hashmap Map id1 = new HashMap(); I inserted some values into both hashmap. For Example, List list1 = new ArrayList(); list1.add("r1"); list1.add("r4"); List list2 = new…
Deepak Shajan
  • 911
  • 1
  • 7
  • 19
76
votes
4 answers

How to replace HashMap Values while iterating over them in Java

I am using a Runnable to automatically subtract 20 from a players cooldown every second, but I have no idea how to replace the value of a value as I iterate through it. How can I have it update the value of each key? public class CoolDownTimer…
Zach Sugano
  • 1,567
  • 5
  • 22
  • 41
75
votes
10 answers

Are mutable hashmap keys a dangerous practice?

Is it bad practice to use mutable objects as Hashmap keys? What happens when you try to retrieve a value from a Hashmap using a key that has been modified enough to change its hashcode? For example, given class Key { int a; //mutable field …
donnyton
  • 5,874
  • 9
  • 42
  • 60
74
votes
4 answers

Usage of integers as hash keys

Is it appropriate to use integers as keys in a Ruby hash? Every example from documentation shows a string or symbol being used as a key, but never an integer. Internally, would integers somehow get converted to strings? I have seen some conflicting…
timpone
  • 19,235
  • 36
  • 121
  • 211
74
votes
2 answers

How does hashing have an o(1) search time?

When we use a HashTable for storing data, it is said that searching takes o(1) time. I am confused, can anybody explain?
algo-geeks
  • 5,280
  • 10
  • 42
  • 54
73
votes
15 answers

How to print all key and values from HashMap in Android?

I am trying to use HashMap in Android sample project. Now, am doing sample project for learn android. I just store keys and values in HashMap, i want to show the keys and their values in EditView. I followed below code in my sample project. But,…
Gopinath
  • 5,392
  • 21
  • 64
  • 97
71
votes
5 answers

Hashmap holding different data types as values for instance Integer, String and Object

I need to create a hashmap with key as integer and it should hold multiple values of different data types. For example if the key is msg id and the values are message of type string timestamp of type time count of type integer version of type…
user2024439
  • 709
  • 1
  • 6
  • 4
70
votes
5 answers

Difference between HashMap and Map in Java..?

Possible Duplicate: Java - HashMap vs Map objects I want to know the difference between HashMap and Map in java..??
user1252812
70
votes
5 answers

Why is Arrays.fill() not used in HashMap.clear() anymore?

I noticed something strange in the implementation of HashMap.clear(). This is how it looked in OpenJDK 7u40: public void clear() { modCount++; Arrays.fill(table, null); size = 0; } And this is how it looks as of OpenJDK 8u40: public…
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
69
votes
6 answers

Find and replace words/lines in a file

I have a file (more specifically, a log4j configuration file) and I want to be able to read in the file and pick out certain lines in the code and replace them. For example, within the file there is a string of text that indicates the directory it…
user459811
  • 2,874
  • 10
  • 37
  • 63
69
votes
7 answers

How to copy HashMap (not shallow copy) in Java

I need to make a copy of HashMap > but when I change something in the copy I want the original to stay the same. i.e when I remove something from the List from the copy it stays in the…
Mathis
  • 691
  • 1
  • 6
  • 8
69
votes
7 answers

Is there a SoftHashMap in Java?

I know there is a WeakHashMap in java.util, but since it uses WeakReferences for everything, which is only referenced by this Map, referenced objects will get lost on the next GC cycle. So it's nearly useless if you want to cache random data, which…
tigger
  • 1,856
  • 3
  • 18
  • 23
69
votes
16 answers

creating Hashmap from a JSON String

creating a hashmap from a json string in java? I have json string like {"phonetype":"N95","cat":"WP"} and want to convert into a standard Hashmap. How can i do it?
curious_cat
  • 886
  • 2
  • 11
  • 14