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

Which one to use: HashMap and ConcurrentHashMap with Future values JAVA?

basically we tend to use ConcuttentHashMap in multi-threading environment. My current code is like this: ExecutorService executor = Executors.newFixedThreadPool(3); Map> myMap = new HashMap
Siddharth Shankar
  • 489
  • 1
  • 10
  • 21
4
votes
4 answers

Is there a julia structure allowing to search for a range of keys?

I know that I can use integer keys for a hashmap like the following example for a Dictionary. But Dictionaries are unordered and do not benefit from having integer keys. julia> hashmap = Dict( 5 => "five", 9 => "nine", 16 => "sixteen", 70 =>…
Hugo Trentesaux
  • 1,584
  • 1
  • 16
  • 30
4
votes
2 answers

How do I create a HashMap with type erased keys?

I want to be able to use a variety of different types as keys in a HashMap, all of which would implement Hash. This seems like it should be possible: from reading the docs it seems that every Hasher will produce a u64 result, so they eventually get…
Alastair
  • 5,894
  • 7
  • 34
  • 61
4
votes
2 answers

Concurrent Hash Map in Kotlin

Is it possible to implement a concurrent hash map purely in Kotlin (without Java dependency)? I am new to Kotlin and it looks like there is no obvious API available in kotlin.collections.
Raj Kukadia
  • 87
  • 2
  • 7
4
votes
2 answers

map.getOrDefault().add() in Java not works

The traditional code works well like below: Map> map = new HashMap<>(); if (!map.containsKey(1)) { map.put(1, new ArrayList<>()); } map.get(1).add(2); Now I'd like to try the magic of getOrDefault: map.getOrDefault(1, new…
LookIntoEast
  • 8,048
  • 18
  • 64
  • 92
4
votes
2 answers

How can I uppercase a MultivaluedMap?

I have a MultivaluedMap object and I want to convert all the keys (not the values) to uppercase. I managed to iterate through the object, but I can't figure out how to reload it. Any ideas?
Bill
  • 291
  • 3
  • 5
  • 14
4
votes
2 answers

Are the keys of JavaScript Objects stored in memory?

I want to know if it uses more memory to store an Array of Objects having the same keys, than just storing an Array of Arrays containing the values. const arrayOfObjects = [ {key1: "val1", key2: "val2", key3: "val4", key4:…
4
votes
3 answers

Flatten nested Map containing with unknown level of nested Arrays and Maps recursively

I have a nested HashMap with String keys that contains either List, Map, or String values. I would like to flatten them like the below. Here is the data: import java.util.*; import java.util.stream.*; public class MyClass { public static void…
Space Impact
  • 13,085
  • 23
  • 48
4
votes
3 answers

Java Map - log message when key is not found in getOrDefault

I have a Map> someMap and I'm retrieving the value based on someKey and for each element of the list of SomeClass I'm performing other operations. someMap.getOrDefault(someKey, new ArrayList<>()).forEach(...) I also want to…
here_to_learn
  • 179
  • 2
  • 11
4
votes
3 answers

Does PowerShell support HashTable Serialization?

If I want to write an object / HashTable to disk and load it up again later does PowerShell support that?
leeand00
  • 25,510
  • 39
  • 140
  • 297
4
votes
2 answers

How go's map hash function workes so different type with "same" value result in different key?

I know the value is not same so I double qouted it, what I want to know is how go's map hash works so that cusKey and a is different in type result in the key is different. package main import ( "fmt" ) type key int const cusKey key =…
Li Jinyao
  • 898
  • 2
  • 12
  • 30
4
votes
1 answer

What do we compare in method put() in Java HashMap?

I opened HashMap source code (Java 8+) and checked the put() method. In Java 7 (and less) the source code was kinda simple, but I can't understand the Java 8+ version. If element in bucket doesn't exist, we just put it into HashMap: if ((p = tab[i…
dogyears
  • 57
  • 4
4
votes
2 answers

Coverting a Java Map to XML using Jackson library

How do I convert a Java Map to XML using Jackson? Version: 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.9.8' Code: import com.fasterxml.jackson.dataformat.xml.XmlMapper; public class MainApp { public static void…
user292049
  • 1,138
  • 1
  • 14
  • 20
4
votes
2 answers

how can store a Json in redis with hashmap( HSET )

i have a question about HSET in redis. As far as i know, redis is a key-value database. that means every thing store as a key-value and we don't have table for example. i wanted to save something in redis so i decided to use Hashmap . since the…
Fateme Ahmadi
  • 344
  • 1
  • 6
  • 18
4
votes
3 answers

How to filter map and return list of values

I am trying to create a function that filters a map that holds a String as a key and a list of Flight objects as values and returns a list of strings. The map represents flight paths and the task is to find the shortest path from the origin to the…
Amaz
  • 43
  • 4