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
3 answers

HashMap gets wrong size

I am trying to export some keys as byte[] from a HashSet to a HashMap and use the HashMap do store pairs of data. However, I am running into a problem, which is that the size om the set is larger than the size of the HashMap, for some reason. I…
user8231110
  • 153
  • 9
4
votes
2 answers

Why does checking if a HashMap has a certain value take very long to execute within a for loop?

I am working with meet-in-the-middle attack on Double-DES. I have implemented the DES encryption/decryption and done the encryptions and now I would like to perform a MITM attack on the Double-DES in order to find the keys. The way I am trying to…
Bab
  • 433
  • 5
  • 12
4
votes
2 answers

Replace HashMap keys with values in Property file in Java

I have to replace HashMap keys based on a property file mapping with old - new key mapping. Is the below approach best way of replacing keys? KeyMapping.properties newKey1 oldLKey1 newKey2 oldKey2 //Load property mapping file ResourceBundle…
user679526
  • 845
  • 4
  • 16
  • 39
4
votes
2 answers

How do I build a Cacher in Rust without relying on the Copy trait?

I am trying to implement a Cacher as mentioned in Chapter 13 of the Rust book and running into trouble. My Cacher code looks like: use std::collections::HashMap; use std::hash::Hash; pub struct Cacher where T: Fn(K) -> V, { …
WarSame
  • 870
  • 1
  • 10
  • 24
4
votes
2 answers

Java 8 Hashmap Internals

I have gone through the implementation of Java 8 Hashmap and arrived with below doubts. Please help me to clarify them: I read in an article which says that, nodes with the same hashcode will be added in same bucket as a linked list. It says that…
Antony Vimal Raj
  • 364
  • 3
  • 14
4
votes
3 answers

nested hashmaps of unknown depth java

I have a requirement in which I need to have an nested hashmap. But the depth would be decided at run time. E.g. If at runtime, user says 3, then my hashmap should be like HashMap>> if he says 4…
maverickprac
  • 543
  • 1
  • 5
  • 8
4
votes
1 answer

Ordering HashMap by the size of the value set

I would like to order a HashMap: Map> unsorted by the size of the value set. I attempted to do it as follows: Map> sorted = unsorted.entrySet().stream() …
montyynis
  • 143
  • 2
4
votes
2 answers

Could you help me to merge values of several maps?

I'm trying to do the following modification: final Map>> scopes = scopeService.fetchAndCacheScopesDetails(); final Map> scopesResponse = scopes.entrySet().stream().collect …
Pasha
  • 1,768
  • 6
  • 22
  • 43
4
votes
1 answer

How to check values in hashmap

I wanted to make a method to check if I can see if each of my piles have 6 cards in it. This is my method public boolean checkIfPileHasSixCards() { map.put("tpile1", tpile1); map.put("tpile2", tpile2); map.put("tpile3",…
Clyde
  • 85
  • 6
4
votes
2 answers

Is it safe to close object before removing it from LinkedHashMap?

I want to override LinkedHashMap's removeEldestEntry(Map.Entry) method to remove stale mappings automatically. Also I want to cleanup the entry that would be removed. The entry is an AutoCloseable object. Can I call close() on it if it's going to…
eriee
  • 416
  • 2
  • 15
4
votes
1 answer

Concurrent_hash_map implementation throwing SIGSEGV

I am trying to use tbb’s concurrent_hash_map to increase my application’s concurrent performance. Read up about it and implemented it according to my application but I am seeing crashes.. So, my application is a multi-threadedd application where I…
Hemant Bhargava
  • 3,251
  • 4
  • 24
  • 45
4
votes
3 answers

Creating a custom iterator for a HashMap

I am trying to implement an iterator that will iterate through the HashMap and its duplicates. For example string.put("a", 1); string.put("a", 2); string.put("b", 3); string.put("b", 4); However with my iterator I only iterate twice, once for where…
Isai
  • 41
  • 2
  • 5
4
votes
2 answers

How to use Timestamp in a Map as key

I am working on a coding challenge on a banking application where I need to fetch number of transactions in last 60 seconds. For that I am using java.sql.Timestamp as a key of a map like below: Map> transactions1 = new…
J. Doe
  • 81
  • 2
  • 3
4
votes
3 answers

HashMap adding object with equals true and same hashcode

I am trying to create custom objects for HashMap and have written code for hashcode and equals method. While adding objects in HashMap, equals method is true and hashcode is returning same value for both objects yet HashMap is adding both objects as…
volga dr
  • 41
  • 1
4
votes
3 answers

Streams on nested map

I have the following usecase. I have a nested map with following structure: Map>> I have to iterate over the map and get the list of CLObject. If the single entry in the list has identifier as null. I have…
user3681970
  • 1,201
  • 4
  • 19
  • 37