HashMap's Iterator to prevent concurrent modification [duplicate] - java

This question already has answers here:
iterating over and removing from a map [duplicate]
(12 answers)
Closed 7 years ago.
The following piece of code, while executed by a single thread, throws a ConcurrentModificationException on line 4:
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
for (String key : map.keySet()) { // Here
map.remove(key);
}
I couldn't find any Map.iterator() or Map.mapIterator() method on HashMap Javadoc.
What should I do?

As you guessed, you need an iterator for removing items during iteration. The way to do it with a Map is to iterate the entrySet() (or, alternatively, the keySet(), if you only need to evaluate the key):
Iterator<Map.Entry<String, String>> entryIter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
iter.remove(); // Probably guard this by some condition?
}

Related

Delete entry from HashMap [duplicate]

This question already has answers here:
Iterate through a HashMap [duplicate]
(7 answers)
Closed 6 years ago.
I have a HashMap:
public static Map<String, Set<String>> adjMap = new HashMap<String, Set<String>>();
adjMap.put(title, new HashSet<String>());
adjMap.get(title).add(cutTitle(graphLink));
Now I want do delete all entries from the values (HashSet), which does not contains as a key.
Here is my code so far:
for(String s: adjMap.keySet()){
for(Set<String> s1: adjMap.values()){
for(String s2: s1){
if(!s.contains(s2)){
s1.remove(s2);
}
}
}
}
But I get an exception:
Exception in thread "main" java.util.ConcurrentModificationException
Iterate your Map
Iterator it = adjMap.entrySet().iterator();
while (it.hasNext())
{
Entry item = it.next();
map.remove(item.getKey());
}
I think for-each loops are not allowed to alter the iterated object. To remove entries you should use an iterator.
Compare to map-Iteration for an example.
You can use ConcurrentHashMap instead, or create a copy of your HashMap and make any changes to the copy.

How to replace ALL keys in java map? [duplicate]

This question already has answers here:
Changing HashMap keys during iteration
(5 answers)
Closed 6 years ago.
I want to replace keys in my map.
I have the following code:
Map<String, Object> map = new HashMap<String, Object>();
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
map.put("d", "4");
map.put("e", "5");
Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> next = iterator.next();
Object o = next.getValue();
//how to add new element ?
//...
iterator.remove();
}
I want to achieve map with keys
a1->1
b2->2
c3->3
d4->4
e5->5
If I use in loop map.put(next.getKey() + next.getValue(), next.getValue()); it will lead to ConcurrentModificationException.
To avoid a ConcurrentModificationException, you need to add the new key/value pairs to a separate map, and then use putAll to add that map into the original one.
Map<String, Object> newMap = new HashMap<>();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
iterator.remove();
newMap.put(...); // Whatever logic to compose new key/value pair.
}
map.putAll(newMap);

How to remove a key from HashMap? [duplicate]

This question already has answers here:
How to remove a key from HashMap while iterating over it? [duplicate]
(2 answers)
Closed 7 years ago.
i have this hashmap
HashMap <Integer,Integer> H = new HashMap <Integer,Integer>();
and when i try to remove the key from HashMap i recive this error
**Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:922)
at java.util.HashMap$KeyIterator.next(HashMap.java:956)
at Livre.montantTotal(Livre.java:42)**
this is my code
for (int e : H.keySet()){
H.put(e, H.get(e)-1);
if (H.get(e) == 0){
H.remove(e);
}
}
You are getting this error because you are trying to remove the element and rearrange the hashmap while its already in use (while looping through it).
To loop through an collection objects in Java, you have an Iterator class which can solve your problem. That class has a remove() method to remove a key pair value from HashMap.
Possible duplicate of How to remove a key from HashMap while iterating over it? and
iterating over and removing from a map
EDIT:
Try this code on Java 7 and earlier versions:
Map<String, String> map = new HashMap<String, String>() {
{
put("test", "test123");
put("test2", "test456");
}
};
for(Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, String> entry = it.next();
if(entry.getKey().equals("test")) {
it.remove();
}
}
In Java 8, you can try this:
map.entrySet().removeIf(e-> <boolean expression> );
You need to use an Iterator to remove from a collection while iterating over it.
for (Iterator<Map.Entry<Integer, Integer>> i = H.entrySet().iterator(); i.hasNext();) {
Map.Entry<Integer, Integer> e = i.next();
int v = e.getValue();
if (v == 1)
i.remove();
else
e.setValue(v - 1);
}
From the Documentation for HashMap.EntrySet() (https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html)
The set is backed by the map, so changes to the map are reflected in
the set, and vice-versa.
You can't change something while you're iterating through it. When you change the HashMap, you change it's keySet too, and since you're iterating through that, Java throws an error. What you might have to do is add every key that needs to be removed to a separate list, then iterate through that list afterward.
Like this:
ArrayList<Integer> otherList = new ArrayList<>();
for(int e : H.keySet()){
h.put(e, H.get(e) - 1);
if(H.get(e) == 0)
otherList.add(e);
}
for(int e : otherList){
H.remove(e);
}

HashMap keys and values [duplicate]

This question already has answers here:
Does Java have a HashMap with reverse lookup?
(7 answers)
Closed 9 years ago.
I have a hash map and values in it. Now i want to set the values in the map as keys and keys as values. Can anyone suggest any idea?
My Map is
Map<String, String> col=new HashMap<String, String>();
col.put("one","four");
col.put("two","five");
col.put("three","Six");
Now i want to create an another map and put it in other way as i told above. ie,
Map<String, String> col2=new HashMap<String, String>();
col.put("five","one");
col.put("four","two");
col.put("Six","three");
Anybody has idea? Thanks
Like so:
Map<String, String> col2 = new HashMap<String, String>();
for (Map.Entry<String, String> e : col.entrySet()) {
col2.put(e.getValue(), e.getKey());
}
Assuming your values are unique in your hashmap, you can do like this.
// Get the value collection from the old HashMap
Collection<String> valueCollection = col.values();
Iterator<String> valueIterator = valueCollection.iterator();
HashMap<String, String> col1 = new HashMap<String, String>();
while(valueIterator.hasNext()){
String currentValue = valueIterator.next();
// Find the value in old HashMap
Iterator<String> keyIterator = col.keySet().iterator();
while(keyIterator.hasNext()){
String currentKey = keyIterator.next();
if (col.get(currentKey).equals(currentValue)){
// When found, put the value and key combination in new HashMap
col1.put(currentValue, currentKey);
break;
}
}
}
Create another Map and iterate through keys/values one by one and put in new Map. finally delete old one.

How to remove a key from HashMap while iterating over it? [duplicate]

This question already has answers here:
iterating over and removing from a map [duplicate]
(12 answers)
Closed 9 years ago.
I am having HashMap called testMap which contains String, String.
HashMap<String, String> testMap = new HashMap<String, String>();
When iterating the map, if value is match with specified string, I need to remove the key from map.
i.e.
for(Map.Entry<String, String> entry : testMap.entrySet()) {
if(entry.getValue().equalsIgnoreCase("Sample")) {
testMap.remove(entry.getKey());
}
}
testMap contains "Sample" but I am unable to remove the key from HashMap. Instead getting error :
"Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)"
Try:
Iterator<Map.Entry<String,String>> iter = testMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String,String> entry = iter.next();
if("Sample".equalsIgnoreCase(entry.getValue())){
iter.remove();
}
}
With Java 1.8 and onwards you can do the above in just one line:
testMap.entrySet().removeIf(entry -> "Sample".equalsIgnoreCase(entry.getValue()));
Use Iterator.remove().

Categories

Resources