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

how to get the lowest float value from the hash map

I have a map which looks like below. What I want to do is get the minimum float value and its corresponding key. Also the float values are like for example 3127668.8 or 1.786453E7 and so on and so forth. How can I achieve this? Map
SASM
  • 1,292
  • 1
  • 22
  • 44
4
votes
2 answers

Convert Map to QueryString

Possible Duplicate: How to convert map to url query string? How to convert Map to query string? For example: MockHttpServletRequest request = getRequest(); HashMap queryString = new HashMap(); …
zen0n
  • 347
  • 2
  • 6
  • 16
4
votes
1 answer

Dictionary/Hashmap implementation using double hashing is stuck in an infinite loop

I'm following this formula from wikipedia: H(i, k) = (H1(k) + i*H2(k)) % size and my H1 is Python's built-in hash() function. H2 is: PRIME - (H1(k) % PRIME) Unfortunately it randomly sticks in an infinite loop after a couple of execution. It…
S.B
  • 13,077
  • 10
  • 22
  • 49
4
votes
2 answers

ConcurrentHashMap foreach loop problem

I have a concurrenthashmap called users. I have user objects in it with some integer keys that is not id. I want to find the user with a given id. Therefore, I check all elements of hashmap and return the user object if it is present. Here is my…
aykut
  • 563
  • 2
  • 6
  • 18
4
votes
4 answers

Reversing a HashMap from Map to Map>

Is there a more elegant/built-in way to reverse the keys and values of a Hashmap? I currently have the following. private Map> reverseMap(Map permissions) { List allow = new ArrayList(); …
alexanderpas
  • 2,712
  • 2
  • 23
  • 33
4
votes
2 answers

boost::unordered_map -- Need to specify a custom hash function for hashing std::set?

I'd like use boost::unordered_map, where key is a std::set. Since a set of integers is no built-in type, I assumed I had to supply my own hash function (or, rather, I was thinking of using boost's hash_range). However, now I tried…
Egon
  • 317
  • 1
  • 3
  • 9
4
votes
4 answers

Java HashMap that takes to much of the memory

The problem is that my hashmap is taking too much space. I wanna know if the code can be done in a more efficient way for not taking that much memory. I have an huge array and the reason why im using HashMap is because I want a fast way to print out…
ZedORYasuo
  • 183
  • 7
4
votes
4 answers

What's the most efficient way to combine objects in a List?

Let's say I have the following list. List test = new ArrayList<>(); //StringInteger is just a pojo with String and int test.add(new StringInteger("a", 1)); test.add(new StringInteger("b", 1)); test.add(new StringInteger("a",…
4
votes
3 answers

Java best practices: Put/Get SubClass objects into HashMap that expects SuperClass objects

Let's say I instantiate a HashMap with SuperClass as value-type. I then add SubClass objects as values to the Map. When I retrieve those values from the Map, they are returned as objects of type SuperClass, which I explicitly cast back to…
Patrick K
  • 41
  • 1
  • 2
4
votes
3 answers

How to increase HashMap value using merge method in Java?

I have the following list and use LinkedHashMap. I want to increase the value of the key by 1 (if the key is not present in the map, it starts from 0, and I add +1): int nums[] = new int[]{4, 10, 5, 4, 2, 10}; Map map = new…
user18952345
4
votes
5 answers

Sort Hashmap keys by numerical value descending order

How can I sort HashMap keys by their numerical value? Currently, in the natural ordering it looks like this: 1 10 13 2 26 29 I want it to look like this: 29 26 13 10 2 1 Any ideas?
Maurice
  • 6,413
  • 13
  • 51
  • 76
4
votes
3 answers

How to remove Keys that would cause Collisions before executing Collectors.toMap()

I have a stream of objects similar to this previous question, however, instead of ignoring duplicate values, I would like to remove any values from that stream beforehand and print them out. For example, from this snippet: Map
Jengels
  • 440
  • 6
  • 15
4
votes
4 answers

Java hashmap search keys for a date

I have a hashmap: Map dateEvent = new HashMap(); where key is a date and time and value is a string. I fill collection with data where date is in format dd.MM.yyyy HH:mm. How I can get all keys with date based on this format: dd.MM.yyyy?
user902201
  • 43
  • 1
  • 1
  • 3
4
votes
5 answers

Find maximum deviation of all substrings

Given a string, find the maximum deviation among all substrings. The maximum deviation is defined as the difference between the maximum frequency of a character and the minimum frequency of a character. For example, in abcaba, a has a frequency of…
codeedoc
  • 454
  • 2
  • 7
  • 16
4
votes
2 answers

HashMap vs ConcurrentHashMap vs LoadingCache(Guava)

To locally cache some data in spring boot application which technique would be better in terms of read/write operations? HashMap vs ConcurrentHashMap vs LoadingCache(Guava library) I tried writing and reading operations on each of these, HashMap was…