Is it safe to change a HashMap key/value during iteration? - java

I have a HashMap. I loop through the map like this:
Map<Long, Integer> map = new HashMap<Long, Integer>();
for (Long key : map.keySet() ) {
int value = map.get(key);
value--;
map.put(key, value);
}
Is the way I'm using to update the map safe? Safe in the sense that it doesn't damage the map because of the iteration.

You could consider writing your code more efficiently as:
Map<Long, Integer> map = new HashMap<Long, Integer>();
for (Entry<Long, Integer> entry : map.entrySet() ) {
entry.setValue(entry.getValue() - 1);
}
This is a micro-optimization, but sometimes it matters, and you don't lose anything. It's shorter and clears up any ambiguity about the safety to boot!

As you can see in the HashMap source code, the put method only modifies the modCount when a new key is provided. modCount is used by the iterator to check for changes, and if such a change occurred between two calls to an iterator's next(), a ConcurrentModificationException would be thrown. This means that the way you are using put is safe.

It is perfectly safe operation that you're doing since you're just changing value of an existing key in the Map.
However if you are ever going to delete an entry from Map then remeber to use Iterator.

Related

ConcurrentModificationException when using iterator to remove entry

I have a simple piece of code that loops through a map, checks a condition for each entry, and executes a method on the entry if that condition is true. After that the entry is removed from the map.
To delete an entry from the map I use an Iterator to avoid ConcurrentModificationException's.
Except my code does throw an exception, at the it.remove() line:
Caused by: java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.remove(Unknown Source) ~[?:1.8.0_161]
at package.Class.method(Class.java:34) ~[Class.class:?]
After a long search I can't find a way to fix this, all answers suggest using the Iterator.remove() method, but I'm already using it. The documentation for Map.entrySet() clearly specifies that it is possible to remove elements from the set using the Iterator.remove() method.
Any help would be greatly appreciated.
My code:
Iterator<Entry<K, V>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<K, V> en = it.next();
if (en.getValue().shouldRun()) {
EventQueue.invokeLater(()->updateSomeGui(en.getKey())); //the map is in no way modified in this method
en.getValue().run();
it.remove(); //line 34
}
}
If you cannot change HashMap to ConcurrentHashMap you can use another approach to your code.
You can create a list of entries containing the entries that you want to delete and then iterate over them and remove them from the original map.
e.g.
HashMap<String, String> map = new HashMap<>();
map.put("1", "a1");
map.put("2", "a2");
map.put("3", "a3");
map.put("4", "a4");
map.put("5", "a5");
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
List<Map.Entry<String, String>> entries = new ArrayList<>();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
if (next.getKey().equals("2")) {
/* instead of remove
iterator.remove();
*/
entries.add(next);
}
}
for (Map.Entry<String, String> entry: entries) {
map.remove(entry.getKey());
}
Please use ConcurrentHashMap in place of HashMap as you are acting on the object in multiple threads. HashMap class isn't thread safe and also doesn't allow such operation. Please refer below link for more information related to this.
https://www.google.co.in/amp/s/www.geeksforgeeks.org/difference-hashmap-concurrenthashmap/amp/
Let me know for more information.
For such purposes you should use the collection views a map exposes:
keySet() lets you iterate over keys. That won't help you, as keys are
usually immutable.
values() is what you need if you just want to access the map values.
If they are mutable objects, you can change directly, no need to put
them back into the map.
entrySet() the most powerful version, lets you change an entry's value
directly.
Example: convert the values of all keys that contain an upperscore to uppercase
for(Map.Entry<String, String> entry:map.entrySet()){
if(entry.getKey().contains("_"))
entry.setValue(entry.getValue().toUpperCase());
}
Actually, if you just want to edit the value objects, do it using the values collection. I assume your map is of type <String, Object>:
for(Object o: map.values()){
if(o instanceof MyBean){
((Mybean)o).doStuff();
}
}

HashMap delete entry AND position

I'm just working with HashMaps and now it pops up a question I actually can't answer by myself...
In my HashMap there are some entries. I'm now searching through all the entries for a certain value. If that value is found It delete it using hashmap.remove();. But I don't "only" want to delete the entry but the whole "position" of the HashMap so that there is no blank space between it. In the end the HashMap shouldn't have any value anymore (I think it will be null then, won't it?)
Is there any possible way to do so?
That's what I got so far but it only deletes the entry not the whole position...
for (Entry<Integer, String> entry : myMap.entrySet()) {
if (entry.getValue().contains("EnterStringHere")) {
myMap.remove(entry);
}
}
This is wrong
for (Entry<Integer, String> entry : myMap.entrySet()) {
if (entry.getValue().contains("EnterStringHere")) {
myMap.remove(entry); // you should pass the key to remove
}
}
But you can't use this way to remove element. You will get ConcurrentModificationException.
You can try this way using iterator to remove element while iterating.
Map<Integer,String> map=new HashMap<>();
map.put(1,"EnterStringHere");
map.put(2,"hi");
map.put(3,"EnterStringHere");
Iterator<Map.Entry<Integer,String>> iterator=map.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<Integer,String> entry=iterator.next();
if(entry.getValue().equals("EnterStringHere")){
iterator.remove();
}
}
System.out.println(map);
Out put:
{2=hi}
You really need to see HashMap#remove()
You cannot remove the entry object from a Map. The remove method expects key.
Instead you can try the below:-
Iterator<Entry<Integer, String>> itr = myMap.entrySet().iterator();
while(itr.hasNext()) {
Entry<Integer, String> entry = itr.next();
if (entry.getValue().contains("EnterStringHere"))
{
itr.remove();
}
}
Also you cannot directly structurally modify a Map while iterating else you will get ConcurrentModification Exception. To prevent this you need to delete using the remove method on the iterator as shown in above code.
Let's say you got a Map<Key,Value> size of 10 and you want to remove 8th key value pair in current Map. What happen is Map become the size of 9 and there will be another key value pair in 8th position.
You can't to beyond that with remove(). You can't remove the position.
But when you use Map.get(removed_key) you will get null since there is no key there now.
Eg:
Map<String,Integer> map=new HashMap<>();
map.put("a",1);
map.put("b",2);
map.put("c", 3);
System.out.println("size of the map "+map.size() +" map is "+map);
map.remove("b");
System.out.println("size of the map "+map.size() +" map is "+map);
System.out.println(map.get("b"));
Out put:
size of the map 3 map is {b=2, c=3, a=1}
size of the map 2 map is {c=3, a=1}
null // you are getting null since there is no key "b"
Adding this to provide answer to your comment,If you want to check whether map is empty. simply use map.isEmpty()
Understanding how HashMap works here Link.
Also see java doc here link.
If you want to set pack your hashmap try to check size of the map then delete one then check size again for example.
hashmap.size(); => 10
hashmap.remove(obj);
hashmap.size() => 9
this means the hashmap is packed and will not have any empty entry. At the end hashmap will automatically will not contain any value in it
Because after a certain time I need to check if the HashMap is empty. But another answer seems to get the hint I needed. If I delete the value the entry will be null? Can i do a check if every entry is null easily or do i have to iterate over every entry again?
You do not delete a value from a Map you delete a mapping. this code does not delete any thing:
myMap.remove(entry);
because you pass the entry object, you need to pass the key of the mapping on order to delete it, see Map.html#remove docs.
thus
myMap.remove(entry.getkey());
However with the current approach you will run in ConcurrentModificationException. If it didnt till now it's just because your code didn't delete anything, because you pass the entry object
If you delete the mapping from the map, that mapping will no longer exist in the map. Whether the bucket is null or not is implementation detail, but when you query a mapping that was deleted using the given key you'll get null as return value. If you add another mapping with the same key you will get taht mapping again.
You can check if a map is empty using Map#isEmpty, thus you dont need to check if every entry is null or iterate over the whole map to do so.
You can check if a map contain a mapping for a key using Map.#containsKey
You can check if a map caintains at least one mapping for a value using Map#containsValue
the correct way to delete etriey from a map while iteration it to use an iterator
Iterator<Entry<Integer, String>> iterator = myMap.entrySet().iterator();
while(iterator.hasNext()) {
Entry<Integer, String> entry = iterator.next();
if (entry.getValue().contains("foo")) {
iterator.remove();
}
}
Since you have Map<Integer, String> I assume that the position you mean is the integer key, where you do something like myMap.put(1, "."), myMap.put(2, ".."), myMap.put(3, "...") and so on. In that case if you remove the mapping for the key 1 for example, the postion, i.e the mapping {1 : "."} will no longer exist in the map.
OK I got a codeable example that's pretty easy.
public class TestingThingsOut {
public static void main(String [] args) {
HashMap<Integer, String> myMap = new HashMap<Integer, String>();
myMap.put(123, "hello");
myMap.put(234, "Bye");
myMap.put(789, "asdf");
System.out.println(myMap); // it says:
{789=asdf, 234=Bye, 123=hello}
System.out.println(myMap.size()); // it says: "3"
for (Entry<Integer, String> entry : myMap.entrySet()) {
if (entry.getValue().contains("hello")) {
myMap.remove(entry);
}
}
System.out.println(myMap); // it says:
{789=asdf, 234=Bye, 123=hello}
System.out.println(myMap.size()); // it says: "3" again
}
}

while iterating hashmap i am not getting ConcurrentModification Exception

value pairs into Hashmap.while iterating that map i am inserting 1 more key value pair at the time i am not getting the Exception. Can any one Help me when Concurrent Modification Exception will come.
Mycode:
public static void main(String[] args) {
Map<String, String> hMap = new HashMap<String, String>();
hMap.put("FIRST", "1");
hMap.put("SECOND", "2");
hMap.put("THIRD", "3");
hMap.put("FOURTH", "4");
hMap.put("FIFTH", "5");
hMap.put("SIXTH", "6");
System.out.println("HashMap before iteration : " + hMap);
Iterator<String> hashMapIterator = hMap.keySet().iterator();
while (hashMapIterator.hasNext()) {
String key = hashMapIterator.next();
if (key.equals("FOURTH")) {
System.out.println("key = " + key);
hMap.put("sfsfsfsf2", "dsgfdsg");
}
}
System.out.println("HashMap after iteration : " + hMap);
}
You may get a ConcurentModificationException but there is no garantee. The Map (and HashMap) contract for the keyset is :
If the map is modified while an iteration over the set is in progress
(except through the iterator's own remove operation), the results of
the iteration are undefined.
Some implementations try to fail fast, but again there is no garantee. The Hashmap javadoc even says :
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 ConcurrentModificationException occurs because both the Iterator and Map#put can modify the Map at the same time. To circumvent that, create a temporary storage for your #put operations:
Map<String, String> tmp = new HashMap<String, String>();
//...
Iterator<String> iter = hMap.keySet().iterator();
while(iter.hasNext()) {
//...
tmp.put("asdfasdf", "aasdfasdfas");
}
for (Entry<String, String> ops : tmp.entrySet())
hMap.put(ops.getKey(), ops.getValue());
A simple observation: If #put adds a new key while iterating, how should the iterator know that it must possibly "jump back" in its new iteration sequence to get to the newly added key as well?
Other Maps
My guess is that the ConcurrentModificationException might not occur if the key from #put is added to the entrySet such that its position (in the Iterator) is after the currently iterated element, so that the "old" Iterator is still consistent with the "new" entrySet because it has delivered the elements in the same order a "new" Iterator would have. But that's just my guess as to why it may not occur. Coding like this is really bad though, since existing code would depend on the implementation details of hashCode of the key-Class.
HashMap
The implementation of HashMap keeps track of structural modifications to the Map:
The number of times this HashMap has been structurally modified Structural modifications are those that change the number of mappings in the HashMap or otherwise modify its internal structure (e.g., rehash). This field is used to make iterators on Collection-views of the HashMap fail-fast. (See ConcurrentModificationException).
And when an HashIterator is requested to advance it checks if the modCount has changed since its creation. If it has, it throws a ConcurrentModificationException. This means it won't be thrown if you only change a value associated to a key, but don't change the keys in any way.

Retrieving the previous key-map value before it was overwritten in a HashMap

I have created a HashMap as per my code...
HashMap map=new HashMap();//HashMap key random order.
map.put("Amit","Java");
map.put("Saral","J2EE");
map.put("Saral","Andriod");//same key but different value
map.put("Nitin","PHP");
map.put("hj","Spring1");
System.out.println("There are "+map.size()+" elements in the map.");
System.out.println("Content of Map are...");
Set s=map.entrySet();
Iterator itr=s.iterator();
while(itr.hasNext()){
Map.Entry m=(Map.Entry)itr.next();
System.out.println(m.getKey()+"\t"+m.getValue()+"\t"+ m.hashCode());
}
When I execute this code, the value for key=Saral is Android. Is there any way that I can get the previous value for this key, which was J2EE?
No, you can't have that with a standard HashMap. The easiest solution would be to store a List as value in the map though, and then you can add multiple items to the list (Btw you should use generic collections too). To simplify, you could use a helper method like this:
void addToMap(Map<String, List<String>> map, String key, String value) {
List<String> list = map.get(key);
if (list == null) {
list = new ArrayList<String>();
map.put(key, list);
}
list.add(value);
}
Map<String, List<String>> map = new HashMap<String, List<String>>();
addToMap(map, "Amit", "Java");
addToMap(map, "Saral", "J2EE");
addToMap(map, "Saral", "Andriod");//same key but different value
addToMap(map, "Nitin", "PHP");
addToMap(map, "hj", "Spring1");
...
The helper method here is just an illustration - a full, robust implementation may need to include e.g. checks for duplicate values, depending on whether you allow them. If not, you may prefer using a Set instead of List.
Update
To print out the contents of this map, you need to use an embedded loop to iterate through the list of values for each map entry (btw you can use a foreach loop instead of an iterator):
for (Map.Entry<String, List<String>> m : map.entrySet())
{
for (String v : m.getValue())
{
System.out.println(m.getKey()+"\t"+v+"\t"+ m.hashCode());
}
}
A Map can contain at most one entry per key, so when you call map.put("Saral","Andriod"), the old "J2EE" value is removed. To support multiple values per key, you would need to maintain a Map<String, List<String>> or else a multi-map implementation such as Guava's Multimap.
As a side note I would recommend you start using generics, for example Map<String, String>, Iterator<String>, etc. for type safety at compile time.
The old value is overwritten (replaced). There will be only one mapping (entry) for one unique key. There fore it does not exist anymore so you can not retrieve it.
You cannot do this with standard implementations of Map that Java provides. However there are implementations of MultiMap (that's basically what you're after).
One example is this one from Google:
http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/collect/Multimap.html
Note that you won't be able to just get this one interface, you'll need a few classes along with it.
As other have said, this won't work with a standard Map. However, Google's Guava provides a MultiMap interface, which you can use to store multiple values with a single key.
Example of use:
Multimap<String,String> multiMap = ArrayListMultimap.create();
multiMap.put("color", "red");
multiMap.put("color", "blue");
System.out.println(multiMap.get("color")); //returns a ["red', "blue"] list

Using the keySet() method in HashMap

I have a method that goes through the possible states in a board and stores them in a HashMap
void up(String str){
int a = str.indexOf("0");
if(a>2){
String s = str.substring(0,a-3)+"0"+str.substring(a-2,a)+str.charAt(a-3)+str.substring(a+1);
add(s,map.get(str)+1);
if(s.equals("123456780")) {
System.out.println("The solution is on the level "+map.get(s)+" of the tree");
//If I get here, I need to know the keys on the map
// How can I store them and Iterate through them using
// map.keySet()?
}
}
}
I'm interested in the group of keys. What should I do to print them all?
HashSet t = map.keySet() is being rejected by the compiler as well as
LinkedHashSet t = map.keySet()
Use:
Set<MyGenericType> keySet = map.keySet();
Always try to specify the Interface type for collections returned by these methods. This way regardless of the actual implementation class of the Set returned by these methods (in your case map.keySet()) you would be ok. This way if the next release the jdk guys use a different implementation for the returned Set your code will still work.
map.keySet() returns a View on the Keys of the map. Making changes to this view results in changing the underlying map though those changes are limited. See the javadoc for Map:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet%28%29
Map<String, String> someStrings = new HashMap<String, String>();
for(Map.Entry<String, String> entry : someStrings.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}
This is how I like to iterate through Maps. If you specifically want just the keySet(), that answer is elsewhere on this page.
for ( String key : map.keySet() ) {
System.out.println( key );
}
Set t = map.ketSet()
The API does not specify what type of Set is returned.
You should try to declare variables as the interface rather than a particular implementation.
Just
Set t = map.keySet();
Unless you're using an older JDK, I think its a little cleaner to use generics when using the Collections classes.
So thats
Set<MyType> s = map.keySet();
And then if you just iterate through them, then you can use any kind of loop you'd like. But if you're going to be modifying the map based on this keySet, you you have to use the keySet's iterator.
All that's guaranteed from keySet() is something that implements the interface Set. And that could possibly be some undocumented class like SecretHashSetKeys$foo, so just program to the interface Set.
I ran into this trying to get a view on a TreeSet, the return type ended up being TreeSet$3 on close examination.
Map<String, Object> map = new HashMap<>();
map.put("name","jaemin");
map.put("gender", "male");
map.put("age", 30);
Set<String> set = map.keySet();
System.out.println("this is map : " + map);
System.out.println("this is set : " + set);
It puts the key values in the map into the set.
From Javadocs HashMap has several methods that can be used to manipulate and extract data from a hasmap.
public Set<K> keySet()
Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
Specified by:
keySet in interface Map
Overrides:
keySet in class AbstractMap
Returns:
a set view of the keys contained in this map
so if you have a map myMap of any datatype , such that the map defined as map<T> , if you iterate it as follows:
for (T key : myMap.keySet() ) {
System.out.println(key); // which represent the value of datatype T
}
e.g if the map was defined as Map<Integer,Boolean>
Then for the above example we will have:
for (Integer key : myMap.keySet()){
System.out.println(key) // the key printed out will be of type Integer
}

Categories

Resources