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
68
votes
4 answers

What is the time complexity of HashMap.containsKey() in java?

I need to know: What is the time complexity of HashMap.containsKey() in java?
Hossein
  • 40,161
  • 57
  • 141
  • 175
68
votes
8 answers

How does one convert a HashMap to a List in Java?

In Java, how does one get the values of a HashMap returned as a List?
sparkyspider
  • 13,195
  • 10
  • 89
  • 133
68
votes
8 answers

How can I move a particular HashMap entry to the end of the map?

How to move a particular HashMap entry to the last position? For example, I have HashMap values like this: HashMap map = new HashMap(); // map = {Not-Specified 1, test 2, testtest 3}; "Not-Specified" may come in any…
Gnaniyar Zubair
  • 8,114
  • 23
  • 61
  • 72
68
votes
8 answers

Collectors.groupingBy doesn't accept null keys

In Java 8, this works: Stream stream = Stream.of(ArrayList.class); HashMap> map = (HashMap)stream.collect(Collectors.groupingBy(Class::getSuperclass)); But this doesn't: Stream stream =…
Marcelo Glasberg
  • 29,013
  • 23
  • 109
  • 133
68
votes
6 answers

Is the order of values retrieved from a HashMap the insertion order

I am trying figure out the order in which the values in a HashMap are/can be retrieved. Heres the code snippet for the same. import java.util.HashMap; public class HashMapExample { public static void main(String[] args) { …
javagurl
  • 683
  • 1
  • 6
  • 5
68
votes
11 answers

How to get values and keys from HashMap?

I'm writing a simple edit text in Java. When the user opens it, a file will be opened in JTabbedPane. I did the following to save the files opened: HashMap hash = new HashMap(); Where Tab will receive the values, such as:…
user2279895
66
votes
7 answers

Ruby Hash Whitelist Filter

I am trying to figure out how I can filter out key and value pairs from one filter into another For example I want to take this hash x = { "one" => "one", "two" => "two", "three" => "three"} y = x.some_function y == { "one" => "one", "two" =>…
stellard
  • 5,162
  • 9
  • 40
  • 62
66
votes
3 answers

Java stream - Sort a List to a HashMap of Lists

Let's say I have a Dog class. Inside it I have a Map and one of the values is Breed. public class Dog { String id; ... public Map } I want to get a Map of Lists: HashMap> // breed to a…
Bick
  • 17,833
  • 52
  • 146
  • 251
65
votes
4 answers

How to merge Ruby hashes

How can I merge these two hashes: {:car => {:color => "red"}} {:car => {:speed => "100mph"}} To get: {:car => {:color => "red", :speed => "100mph"}}
skyporter
  • 847
  • 1
  • 7
  • 14
65
votes
4 answers

Implementing a HashMap in C

How to go about creating a Hashmap in C from scratch as is present in C++ STL? What parameters would be taken into consideration and how would you test the hashmap? As in, what would the benchmark test cases be which you would run before you could…
Thunderboltz
  • 1,597
  • 3
  • 14
  • 16
65
votes
7 answers

Java : Iteration through a HashMap, which is more efficient?

Given the following code, with two alternative ways to iterate through it, is there any performance difference between these two methods? Map map = new HashMap(); //populate map //alt. #1 …
bguiz
  • 27,371
  • 47
  • 154
  • 243
65
votes
4 answers

Warning shows when i use Hash Map In android(Use new SparseArray)

I am new to developing in android. In my android app I'm using HashMap, but I'm getting a warning: **"Use new SparseArray(...) instead for better performance"** What does this mean, and how can I use SparseArray instead?
Naveen Kumar
  • 3,738
  • 4
  • 29
  • 50
65
votes
9 answers

Hash keys / values as array

I cannot find the JavaScript equivalent of PHP array_keys() / array_values(). For people unfamiliar with PHP given the following JavaScript hash: var myHash = {"apples": 3, "oranges": 4, "bananas": 42} How can I get an array of keys,…
greg0ire
  • 22,714
  • 16
  • 72
  • 101
64
votes
1 answer

What hash algorithm does Python's dictionary mapping use?

I was messing around with making a command line parser and was wondering what kind of hash algorithm python dict's use? The way I have it set up, I have a pattern match algorithm which matches tokenized input sequences with a dictionary key. Some…
Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
64
votes
6 answers

Is hash_map part of the STL?

Quick question...Is hash_map part of the STL?
Jake
  • 2,877
  • 8
  • 43
  • 62