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

How can i sort HashMap order by their values in Kotlin?

Here is my example, how can i do that in Kotlin? var hashMapForTry = HashMap() hashMapForTry.put("Hi",5) hashMapForTry.put("What",7) hashMapForTry.put("How",2) hashMapForTry.put("Go",1) hashMapForTry.put("Ford",9)
commandiron
  • 1,019
  • 1
  • 9
  • 25
4
votes
3 answers

Laziness of eviction in Guava's maps

Current eviction algorithm for maps is quite lazy. It looks like expired objects are evicted only when the data structure is accessed. For example, the map from addresses to indexers defined as: ConcurrentMap indexers = new…
Viliam
  • 4,404
  • 3
  • 28
  • 30
4
votes
1 answer

Why HashMap resize when it hits TREEIFY_THRESHOLD value which is not required?

I know How HashMap works internally. But while checking HashMap code with TreeNode implementation I'm not getting the goal behind the increasing size of bucket but not treeify until bucket size hits MIN_TREEIFY_CAPACITY = 64. Note: I've considered…
Vicky Thakor
  • 3,847
  • 7
  • 42
  • 67
4
votes
3 answers

Which Java collection is suitable for finding filenames with max timestamp in a Huge arraylist?

We have a huge list which updates daily. We get daily files multiple times a day with same names and each file has different timestamps (format can be any way but it includes dd,mm,yy hour, minutes, seconds)…
fatherazrael
  • 5,511
  • 16
  • 71
  • 155
4
votes
1 answer

How to configure Spring Redis Configuration to use Hash instead of string serialization

For a Java POJO, I want to cache it to Redis using Spring's @Cacheable, @CachePut, and @CacheEvict, however I'd prefer to use Redis' Hash capabilities instead of just serializing the POJO into a String. Essentially, I would like to be able to use…
4
votes
6 answers

Explanation about HashMap hash algorithm in this example

I was trying to solve this question: Given an array of integers with only 3 unique numbers print the numbers in ascending order (with their respective frequencies) in O(n) time. I wanted to solve it without using the counting sort algorithm, So…
Daniel_Kamel
  • 610
  • 8
  • 29
4
votes
6 answers

How to get attributes for HashMap value?

"my" code: public void iterateHashmap2() { HashMap hashmap = this.media; Iterator it = hashmap.keySet().iterator(); while (it.hasNext()) { Object key = it.next(); Object val = hashmap.get(key); // doesn't…
OP2011
  • 41
  • 1
  • 1
  • 2
4
votes
2 answers

Difference between a hashmap and an array in time complexity of a lookup

If I have to know the key to get the value in a hashmap (for time complexity O(1)), why is it any different than getting a value inside an array when knowing the index (O(1) as well)? In other words, a hashmap is considered having O(1) complexity…
David
  • 159
  • 1
  • 14
4
votes
2 answers

HashMap with only most recent entries

I recently had an interview where the interviewer asked me to create a HashMap that has a maximum of 7 key/value pairs. If an 8th key/value pair is added, the first key/value pair should be removed and the eighth inserted to replace it, etc. What's…
Tanu Garg
  • 3,007
  • 4
  • 21
  • 29
4
votes
4 answers

Java Concurrency and Add-Only HashMaps

I'm writing a program that makes extensive use of large HashMaps. It is multithreaded, so I've used read-write locks when accessing it. However, it has a special property that I'd like to exploit. After data is "put" into the HashMap, that data is…
Ethan
  • 565
  • 1
  • 7
  • 17
4
votes
3 answers

How to convert LinkedHasMap Values into ArrayList/Array in right order?

I'm getting LinkedHashMap grades = courses.get(choise).getGrades(); I need to save the grades values in an array/arraylist. I'm able to get values and keys in loop String key = ""; String value = ""; for (Object o : grades.keySet()){ key =…
G. Dawid
  • 162
  • 1
  • 11
4
votes
4 answers

What are the benefits of using Map over ArrayList of costume class

I am learning Java now and I am learning about different kinds of collections, so far I learned about LinkedList, ArrayList and Array[]. Now I've been introduced to Hash types of collections, HashSet and HashMap, and I didn't quite understand why…
elii236
  • 98
  • 4
4
votes
3 answers

An "append-only" / "write-only" hash in Ruby

I'm looking for a kind of "append-only" hash where keys may only be set once. For example: capitals = AppendOnlyHash.new capitals['france'] = 'paris' capitals['japan'] = 'tokyo' capitals['france'] = 'nice' # raises immutable exception Any library…
mahemoff
  • 44,526
  • 36
  • 160
  • 222
4
votes
1 answer

How the Java HashMap internal data structure changes during rehashing?

I am trying to write demo code to show rehashing is happening in Hashmap when the map size exceeds the load factor threshold. How can I prove rehashing is happening internally . Also I want to prove that eventhough the old entries are moved to new…
JavaUser
  • 25,542
  • 46
  • 113
  • 139
4
votes
1 answer

LinkedHashMap changes to HashMap and crashes in flink data stream operators

Given this dummy code: 1 case class MyObject(values:mutable.LinkedHashMap[String, String]) ... 2 implicit val typeInfoString:TypeInformation[String] = TypeInformation.of(classOf[String]) 3 implicit val…
user826955
  • 3,137
  • 2
  • 30
  • 71