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

groupBy on List as LinkedHashMap instead of Map

I am processing XML using scala, and I am converting the XML into my own data structures. Currently, I am using plain Map instances to hold (sub-)elements, however, the order of elements from the XML gets lost this way, and I cannot reproduce the…
user826955
  • 3,137
  • 2
  • 30
  • 71
4
votes
2 answers

Using HashMap with Integers ( indices ) as keys vs using an ArrayList

So I'm currently making my own version of Pokemon replicated in Java. I've only gotten familiar with more advanced data structures very recently and I'm still not sure when one should be more appropriate than the other. Basically, I want to store a…
PreciseMotion
  • 330
  • 1
  • 14
4
votes
12 answers

Java8: Create HashMap with character count of a String

Wondering is there more simple way than computing the character count of a given string as below? String word = "AAABBB"; Map charCount = new HashMap(); for(String charr: word.split("")){ Integer added =…
OTUser
  • 3,788
  • 19
  • 69
  • 127
4
votes
1 answer

using hashCode to return huge Integer ids for HashMap

HashMap works with fixed length arrays internally and indexes where values will are stored are based on hash of the key, and in case of collion for hash it will make a linked list on that index and then will use equals method to return the correct…
Toseef Zafar
  • 1,601
  • 4
  • 28
  • 46
4
votes
2 answers

Return Map of Map without side-effects using Java 8 Stream

How do I put/add eServiceReportsMapByBatchFile with key oldReportId to eServiceReportMap without side-effects? Map>> eServiceReportMap = new HashMap<>(); reports.forEach(report -> { String oldReportId =…
Julez
  • 1,010
  • 22
  • 44
4
votes
3 answers

Getting 'Type mismatch: cannot convert from ArrayList> to List>' while instantiating a list of maps

List> recordMapList = new ArrayList>(); The above line gives the error: Type mismatch: cannot convert from ArrayList> to List> But the issue goes away if use HashMap instead of Map in the left hand…
DockYard
  • 989
  • 2
  • 12
  • 29
4
votes
3 answers

Mapping large set of Keys to a small set of Values

If you had 1,000,000 keys (ints) that mapped to 10,000 values (ints). What would be the most efficient way (lookup performance and memory usage) to implement. Assume the values are random. i.e there is not a range of keys that map to a single…
Chris
  • 1,299
  • 3
  • 18
  • 34
4
votes
2 answers

filter a stream using collect() instead of filter()

I have the list that contains data that looks like this game_id | user_id | status 1 1 STARTED 2 1 FINISHED 1 2 STARTED 2 2 FINISHED I want to collect this list into two maps (or…
lapots
  • 12,553
  • 32
  • 121
  • 242
4
votes
1 answer

How does a HashMap identify which locations in the internal array contain elements?

I am trying to build a simple implementation of the HashMap class in Java, for learning purposes. I know how rehashing works (Rehashing process in hashmap or hashtable). When rehashing, all the elements present in the internal array are identified…
Victor Durojaiye
  • 162
  • 1
  • 10
4
votes
4 answers

Sort Map in Ascending Order by Key

I'm attempting to sort a Map in ascending order based on the keys. Given the Map: Map map = new LinkedHashMap(); map.put(5, "five"); map.put(1, "one"); map.put(3, "three"); map.put(0, "zero"); I would like the…
Alan Cook
  • 342
  • 3
  • 14
4
votes
3 answers

Java Sorting a Map using Steams VS TreeMap

Consider the following Java HashMap. Map unsortMap = new HashMap(); unsortMap.put("Z", "z"); unsortMap.put("B", "b"); unsortMap.put("A", "a"); unsortMap.put("C", "c"); Now I wish to sort this Map by Key. One option…
Keet Sugathadasa
  • 11,595
  • 6
  • 65
  • 80
4
votes
1 answer

Time Complexity of Looping over an ArrayList and putting values in HashMap vs. just searching the ArrayList

If you start with an ArrayList, is there a time benefit to for-looping over the ArrayList and putting the values into a HashMap with a useful key for searching? Or does the looping of the ArrayList pretty much negate any benefit you would gain…
Crizly
  • 971
  • 1
  • 12
  • 33
4
votes
5 answers

Java 8 Stream filter map in map -- Map>

How to filter a Map> using Java 8 Filter? I have to filter only when any of employee in the list having a field value Gender = "M". Input: Map> Output:…
user1578872
  • 7,808
  • 29
  • 108
  • 206
4
votes
7 answers

Efficiently iterate through all MATCHING keys in a hashmap?

I have a HashMap with millions of entries. Need to retrieve all entries whose keys match a specific set of criteria (in this case, each key is an object with two integer properties; I need to retrieve all keys where each of these integers fall…
DanM
  • 7,037
  • 11
  • 51
  • 86
4
votes
2 answers

Hibernate: Map Two Columns to a HashMap's Key and Value

I have a database with an object, which has translations. There are 2 tables: table Object which has id and more properties and table 'object_translation' which has object_id, language (varchar) and translation (varchar) I would like to map this to…
Thomas Stubbe
  • 1,945
  • 5
  • 26
  • 40