I would like to have a HashMap
with only one key-value object.
I have created the following HashMap
:
HashMap <Integer,String>DocsCollection = new HashMap <Integer,String>();
In the HashMap I would like to have only one entry/object. The key type is an Integer. The value type is a String.
e.g. = <1,"foo.txt">
Every time I find a specific word in a file I would like to
Increment the counter in key
Add the new file in the value
e.g. Let's say that I'm searching for the word "Hello" in a DocsCollection
,
I have to store for every appearance of the word "Hello" the term frequency and concatenate the new file to the previous value.
<3,"foo.txt,hello.txt,test.txt">
3 means that I've found the word "Hello" in three files.
and the Value consists of the files where the word was found
If I use the method put, a new entry is created in the HashMap
cause the key changes.
It's not stable. It begins with "1" but when I find the word second time , the key increments and then the put method inserts a new entry with a new key
But i would like to have only one entry and modify the key.
Can this be done?
How can i have only one object in a HashMap and modify the key every time?
DocsCollection.put(2,"foo.txt,hello.txt");
Thanks, in advance
A HashMap in Java can have a maximum of 2^30 buckets for storing entries - this is because the bucket-assignment technique used by java. util. HashMap requires the number of buckets to be a power of 2, and since ints are signed in Java, the maximum positive value is 2^31 - 1, so the maximum power of 2 is 2^30.
HashMap and LinkedHashMap classes are the widely used implementations of the Map interface. But the limitation of the Map interface is that multiple values cannot be stored against a single key. To overcome this issue, we can either use Guava Collections or Apache Common Collections.
You can't have an hash map with multiple keys, but you can have an object that takes multiple parameters as the key. Create an object called Index that takes an x and y value.
HashMap uses a linked list in case of collision and objects will be stored in the next node of the linked list. Also, HashMap stores both key and value tuples in every node of the linked list in the form of Map.
Try this way:
DocsCollection = Collections.singletonMap(2, "foo.txt,hello.txt");
this Map can't be modified, if you want to to that just do this:
DocsCollection = Collections.singletonMap(3, "foo.txt,hello.txt");
The Map approach might not be the best. The issue is you are changing your key value.
Note it might be better to just have a List<String>
, and everytime you match the word, just add the file to the list. You can get the count easily with list.size()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With