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

Why do we need hashcode and bucket in LinkedHashMap

Lately,I've been going through implementations of Map interface in java. I understood HashMap and everything made sense. But when it comes to LinkedHashMap, as per my knowledge so far, the Entry has key, value, before and after. where before and…
Arun Gowda
  • 2,721
  • 5
  • 29
  • 50
4
votes
2 answers

List of comma separated String to Map of list using java 8

I have a list of comma separated strings - List: format = ----- values ----- ab123,X cd123,Y ab123,Y cd123,Z ------------------ I want to convert this list to Map> using java 8 where key would be the unique…
bpa.mdl
  • 396
  • 1
  • 5
  • 19
4
votes
7 answers

A hashmap inside of a hasmap print out

I am trying to print out a hashmap that contains A character as the key and the value as another hashmap with Integer and Double I have this so far but isn't working. HashMap> MapInsideOfAMap = calc.MapInAMap(abc); …
2345678
  • 69
  • 7
4
votes
2 answers

Get the list from Map and filter using groovy

I am trying to get a list from a map and based on id's list and want to retrieve the values (list) based on age (age > 35) def people = [ "1": [[name:'Bob', age: 32, gender: 'M'],[name:'Johnny', age: 36, gender: 'M']], "3": [[name:'Claire', age:…
p_nair
  • 57
  • 1
  • 1
  • 5
4
votes
1 answer

Print random key followed by specific value?

I'm pretty new to Java and in an effort to learn more I'm trying to make a game whereby you're given a random lyric from a song, and then the song title and artist. This would be pretty easy, however I wanted the lyric to be random, and then print…
user6000127
4
votes
2 answers

Indexing when using a hashmap with streams

I have a HashMap of teams that I need to print out. They need to be indexed and sorted by some parameters(not relevant). Everything works fine except for the indexing part which I got working in a way but it doesn't feel right. int i=0; public void…
Andrej
  • 43
  • 5
4
votes
4 answers

Grouping of FizzBuzz numbers

I am trying to code FizzBuzz problem in Java8. It is working fine and I am getting desired output. For the number divisible by "3", it should return "Fizz", for the number divisible by "5", it should return "Buzz" and for the number divisible by…
Achal
  • 133
  • 2
  • 12
4
votes
3 answers

Kotlin HashMap contain keys using an array

Is there any way to check a HashMap if it contains a certain set of keys which keys are given in an array. When I try something like the code below it returns false. map.containsKey(arrayOf("2018-01-16")) If I try the following code it works but I…
Nick Pampoukidis
  • 702
  • 8
  • 28
4
votes
3 answers

In C# hashtable with objects as values,how do i return the object value

Method CanVote returns true if Age >=18. Constructor of the class assigns default values to all properties. I added the objects to a hashtable with key as Person Name. I need to iterate through the hashtable object to print Name and whether the…
Swetha
  • 63
  • 1
  • 7
4
votes
2 answers

Java 8: Filter an Array(NxM) to create a Map>

I would like to map an NxN array into a Map in Java 8. The idea is that every [i][0] element is a key and every [i][j] with j>0 is a list of values for every key in the map. Thanks for any help. :) This is my class: public class GroupingDishes { …
4
votes
1 answer

Perl: can I skip the intermediate hash variable in this case?

At the moment, I use something like this: my %tmpHash = routineReturningHash(); my $value = $tmpHash{'someKey'}; The only thing I need is $value, I do not need %tmpHash itself. So I am curious to know if there is a way to avoid declaring…
Georg
  • 1,078
  • 2
  • 9
  • 18
4
votes
2 answers

How to create HashMap through JNI then parse to java

Hi I want to secure my web url and app secret keys through Ndk, I want to create hashmap in app and also store key values statically then parse to java, I follow Stackoverflow answer like Create HashMap also JNI passing objects from C++ to Java some…
4
votes
3 answers

why hashmap resize based on total size instead of filled buckets

I have a doubt to my mind :: Currently HashMap in java, resizes when totalSize(no of elements inserted) > arrayLength * loadFactor so it doubles the table and rehashes all key-value. But suppose hashcode in Key class is hardcoded to let's say 1,…
Rajat Goyal
  • 465
  • 1
  • 5
  • 20
4
votes
2 answers

Does a concurrent hashmap not require synchronized getters/setters?

If i was using a concurrent hashmap and i had methods which set and got values, as im using a concurrent hashmap would i need to make the getter and setter synchronized? Is this redundant? Is one design better? Also, is a concurrent hashmap without…
Jason
  • 5,451
  • 4
  • 19
  • 12
4
votes
2 answers

How to create a nested dictionary from a csv file with N rows in Python

I was looking for a way to read a csv file with an unknown number of columns into a nested dictionary. i.e. for input of the form file.csv: 1, 2, 3, 4 1, 6, 7, 8 9, 10, 11, 12 I want a dictionary of the form: {1:{2:{3:4}, 6:{7:8}},…
shayelk
  • 1,606
  • 1
  • 14
  • 32
1 2 3
99
100