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
1 answer

Updating elements atomically retrieving from Map using Java 8 parallel streams

I have a parallel stream in which I'm using a Map to mutate the elements. Map> hashmap = foo.getMap(); itemStream.parallel() .filter(Objects::nonNull) .forEach(item -> setProperties(hashmap, item)); The method…
SS'
  • 819
  • 1
  • 8
  • 18
4
votes
8 answers

In Java, empty HashMap space allocation

How can i tell how much space a pre-sized HashMap takes up before any elements are added? For example how do i determine how much memory the following takes up? HashMap map = new HashMap(1000000);
richs
  • 4,699
  • 10
  • 43
  • 56
4
votes
1 answer

How can HashMap.keySet() return a view of keys?

Here is the keySet() function inside java.util.HasMap class : public Set keySet() { Set ks = keySet; if (ks == null) { ks = new KeySet(); keySet = ks; } return ks; } In the comment, it says this…
Bonsaisteak
  • 151
  • 1
  • 8
4
votes
4 answers

Parse a String of key=value to a Map

I'm using an API that gives me a XML and I need to get a map from one tag which is actually a string. Example: Having Billable=7200,Overtime=false,TransportCosts=20$ I need ["Billable"="7200","Overtime=false","TransportCosts"="20$"] The problem is…
Filipe R.
  • 43
  • 4
4
votes
2 answers

ruby hash as key to a hash

Came across the following weird behaviour in ruby 1.8.6, in 1.8.7 it seems to be working correctly. Does anyone know what would have caused this? h = {} key_1 = {1 => 2} key_2 = {1 => 2} h[key_1] = 3 p key_1 == key_2 # => true p h.has_key?(key_2) #…
Jamie Cook
  • 4,375
  • 3
  • 42
  • 53
4
votes
1 answer

How does HashMap in Java use equals() and hashCode() to find objects?

I have defined a Point class as shown below, overriding the equals() and hashCode(). I was expecting that in the main() method, "Key Found" will be printed, but it's not. It was my understanding that Java uses the equals() and hashCode() to add or…
TanM
  • 99
  • 1
  • 6
4
votes
2 answers

How to make a hashmap of dynamic methods in Java

This is a bit of a specific question, but I want to know how to make a HashMap of functions that are obtained in parameters, like so: //All functions will take in string and return void public HashMap functions = new…
Isaac Krementsov
  • 646
  • 2
  • 12
  • 28
4
votes
3 answers

Retrieving an iterator for a HashMap throws a cast exception

I have some relatively simple code I have made that is supposed to retrieve an iterator to a HashMap & print out the key pair values. My problem is that when I go to retrieve the iterator I get this exception thrown. Exception in thread "main"…
Mack
  • 55
  • 1
  • 1
  • 3
4
votes
1 answer

Putting a Hashmap into itself causes strange behavior

The following code creates a hashmap and places it inside of itself. hash = {} hash[hash] = hash hash.keys.first == hash # true hash.values.first == hash # true hash[hash] # nil?? hash.key?(hash) # False hash[hash.keys.first] # nil??? hash[{}] #…
Philip M
  • 149
  • 1
  • 6
4
votes
2 answers

Update a hashmap value, given a key with getOrDefault

I have a HashMap : HashMap hmap = new HashMap<>(); where I want to increase the HashMap value. In order to avoid the nullPointer Exception if the key doesn't exist, I check it! Let's say the data are: //201803271 - 1000 //201803271…
yaylitzis
  • 5,354
  • 17
  • 62
  • 107
4
votes
3 answers

Accesing a method in the last object in a LinkedHashMap

I've got a LinkedHashMap that contains an object at key and one at value. I've used the code yourShots.keySet().toArray()[yourShots.size()-1] to return the last object of the keys. However, I am unable to access a method that the object has. I've…
Brian
  • 119
  • 6
4
votes
1 answer

Method reference on map function, compilation error when the key is of type String

Context: I want to use the function computeIfAbsent on a Map. But, I get a compilation error when I use method reference and the key is a String. I get no compilation error when I use method reference and the key is an Integer. lambda and the…
KeyMaker00
  • 6,194
  • 2
  • 50
  • 49
4
votes
1 answer

What does the Scala interpreter (REPL) print exactly (demonstration with Map and HashMap)?

I have the following two Maps in the REPL in Scala: Case 1 scala> var a1=Map("a" -> "b", "c" -> "d", "e" -> "f", "g" -> "h") a1: scala.collection.immutable.Map[String,String] = Map(a -> b, c -> d, e -> f, g -> h) scala> var a2=Map("a" -> "b","c"…
4
votes
4 answers

Which is better option for HashMap?

Which is better option to use: HashMap with initial size: HashMap hm = new HashMap(10); or HashMap without initial size: HashMap hm = new HashMap()? And why? Also what is loadfactor and modcount in HashMap's property? When I debug my code in…
Harry Joy
  • 58,650
  • 30
  • 162
  • 207
4
votes
2 answers

Detect if a Hashmap with Java Optional has empty values or not?

I want to find out if the HashMap has all its values empty or not. What is the best way to do it other than having to check the value in every entry in the map? HashMap> aMap = new HashMap<>(); aMap.put(new Long(55),…
Ganga
  • 597
  • 2
  • 9
  • 23
1 2 3
99
100