Checking the existence of the key before adding a newhashmap - java

I would like to check if the key already exists before adding an item to the Hashmap. Adds keys from 1 to 20k to the Hashmap, and some may repeat themselves. I would like to check if the key I want to add already exists, if so, I write it to the screen, for example.
I know that you can check if such a key exists with the containsKey method, but I have no idea how to refer to the previous element.
I have absolutely no idea how to start this because I'm just getting started with beanshell :/
Thanks in advance for your help :D
Map MAP_SA = new HashMap()
while(iterator.hasNext()){
org = iterator.next();
MAP_SA.put(org.getExtended(),org.getName());
//here I would like to check if the key repeats before adding anything to the map
}

You can also use the putIfAbsent method on Map interface (available as from JDK 8) which, as the name indicates it, will only add the value only if the specified key does not exist yet.

Assumption:
Keys in Maps are unique, so if you try to insert a new record with a key already present, there will be a "collision" and the value corresponding to that key in the map will be overwritten.
Answering your question:
containsKey() is the correct way, especially in your case where you do a check at runtime, you have the possibility to check at each iteration if the current value you want to insert is already present in the whole map, because containsKey() goes to probe all the keys in the map.
Map MAP_SA = new HashMap()
while(iterator.hasNext()){
org = iterator.next();
if(!MAP_SA.containsKey(org.getExtended8())){ // check all over the map
MAP_SA.put(org.getExtended8(),org.getName());
}else
System.out.println("Error: the key already exists");
}

Related

java hashMap<Integer,String> collision

I'm sorry if this question was already asked, but i don't fine an answer to my question.
I'm working on HashMap i put two values (7,"value test 1") (7,"value test 2)
According to the specification java API HashMap put the first values is replaced by the second .
My question is when comes the resolution of collision ? why my second value is not store in linkedList or store in another place in the hashMap ? Is it due to the equals or hascode method ??
Best Regards
This has nothing to do with hash collision. Hash collisions (ie., keys with the same hashcode()) are handled correctly by the HashMap. In your example, both keys are equal (ie., 7.equals(7) == true), so the old value is replaced.
In the following example
Map<Integer, String> map = new HashMap<>();
map.put(7, "value 1");
map.put(7, "value 2");
System.out.println(map.get(7));
what would you expect in the last line to happen?
Maybe you are looking for a multimap?
Apache Commons
Guava
Stackoverflow
Collision handling takes place if two different keys resolve to the same bucket in the hashmap. In that case the second entry would be put into the linked list.
In your case you replace the entry for the same key (7) and thus there is no collision.
If you need a map that contains multiple values per key either use a Map<key, Set<value>> (you can also use a List etc. instead of a Set) and handle adding/removing to that set yourself or use Apache Commons' MultiMap or Google Guava's Multimap, e.g. HashMultimap.

Removing values from a Java hashmap

Lets say I do Map<String, Integer> map = new HashMap<String, Integer>();
map.containsValue(value) returns true whether or not the value is found in the hashmap. But I found that there is no way to remove a value. Like map.removeValue(value). You can only remove the key, as in, map.removeKey(key).
Now, my question is, does removing the key also remove the value?
So when I search map.containsValue(value), will it return false if I deleted the key associated with the value with map.removeKey?
Now, my question is, does removing the key also remove the value?
Yes. Sort of.
Actually, it removes the specific entry that consists of the key and the value.
If the value is also used in another entry, then that other entry is unaffected, and the value will still show up in the values collection.
So when I search map.containsValue(value), will it return false if I deleted the key associated with the value with map.removeKey?
It depends ... see above.
This information can easily be found by reading the javadoc carefully.
(The problem with the "try it and see" approach is that it is easy to write a "black box" test that will cause you to drawing the wrong conclusions. I would only suggest "try it and see" if the javadoc did NOT contain the information. And I'd add "read the source" ... )

How to get the number of occurrences of a key in HashMap?

I am have the Hashmap like this,
HashMap<String,String> epnSource = new HashMap<String, String>();
Now I have added the keys/values like this,
epnSource.put("10.3.2.227","EPN1");
epnSource.put("10.3.2.227","EPN2");
epnSource.put("10.3.2.166","EPN3");
epnSource.put("10.3.2.166","EPN4");
epnSource.put("10.3.2.161","EPN5");
I am trying to do every time before adding a value, I want to check number of occurrences of a key present in the HashMap. Suppose if key 10.3.2.227 has more than two occurrences I shouldn't added it and go for new one. Any suggestions will be helpful.
Suppose if value 10.3.2.227 has more than two occurrences ...
It won't. The way that you have implemented it, the "10.3.2.227" is a key of the Map, and a given key cannot appear more than once in a Map.
If you want a given key (e.g. "10.3.2.227") to map to multiple values (e.g. "EPN1" and "EPN1"), you need to use either a Map<String,Set<String>> or a MultiMap class from the Apache or Google/Guava collections libraries.
If the map previously contained a mapping for the key, the old value is replaced.
It is not possible duplicate key in HashMap.

How can I use a map for calculations?

I'm working on a program for class. Using a TreeMap to store IDs (String - Key) and earnings amounts (double - value). I'm importing the values from a text file using a Scanner. My problem at the moment is that I need the values to accumulate rather than overwriting with the last value read. So my question is how do you use a Map to do calculations like that? Any help would be appreciated.
There is no implicit functionality in Map. Idea behind your homework assignment is for you to learn how to insert, find, get and replace to/from a Map. There are functions for each of these and ou should use all to get this done.
When adding a new value to your map, if the key already exists, you can get the associated value, add the new value to it, and put it back into the map. Example:
// Assuming that key and value were read from your file, and that
// myMap is declared as "Map<String, Double>"
if (myMap.containsKey (key)) {
double oldValue = myMap.get (key);
value += oldValue;
}
myMap.put (key, value);
1) Check whether value with same key exists in the map
2) If it exists then read it and add the currently read value. Put it back into map

problem getting value from HashMap

Hi all I'm using a HashMap to hold one of my object with a string key. when I put an object with a key it has no problem, when I put my second object I got my object added but can't get it with its key. Somewhat it goes to somewhere that is "next". I took a screenshot from debug mode (eclipse), below
although size shows 2, I can't see my second item in hashmap, but in other hashmap's next node.
To note something I use my key like in a form "name.tag", tag and name in same time can never be the same, but "tag" can be the same. does hashmap has something to do with dot operator when evaluating keys? I hope I could write clearly,
Thanks in advance
Edit:
Here is a piece of code I use to create my hashmap
private HashMap<String,ParameterItem> parseParametersNode(DataModel parent,Element element){
NodeList parameterChilds=element.getChildNodes();//gep element parameters
HashMap<String, ParameterItem> parameterItems=new HashMap<String, ParameterItem>();
for(int i=0;i<parameterChilds.getLength();i++){
if(parameterChilds.item(i).getNodeType()==Node.ELEMENT_NODE){
Element el=(Element) parameterChilds.item(i);
NamedNodeMap atts=el.getAttributes();
ParameterItem item=new ParameterItem();
for(int j=0;j<atts.getLength();j++){
Attr attribute=(Attr) atts.item(j);
String attributeValue=attribute.getValue();
String attributeName=attribute.getName();
item.setParsedProperty(attributeName, attributeValue);
} /*check attributes later*/
//finish loop and insert paramitem to params
String key="key"+i;
if(item.getTag()!=null && item.getName()!=null)
key=item.getName()+"."+item.getTag();
parameterItems.put(key, item);
// testParam=item;
// parameterItems.put(key, testParam);
}
}
return parameterItems;
}
There is not really a problem here: you have a hash collision. That is, both of your keys have been placed in the same hash bucket. It appears you have only four buckets (odd, I thought the initial default was 10 or 16), so the chance of that with random data is 25 percent. Your size incremented just fine. The next is the internal implementation’s way of pointing to the next element in the same bucket. If the number of elements in each buckets gets too big, Java will internally rehash into more buckets.
I do not see why you need a HashTable here since you are numbering your keys consecutively (you could use an ArrayList), but maybe this is just starter code and your real use case is different.
You have the code:
String key="key"+i;
but right after this you set key again not adding to it:
if(item.getTag()!=null && item.getName()!=null)
key=item.getName()+"."+item.getTag();
Should this be key +=item.getName()+"."+item.getTag(); ?

Categories