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);
}
Related
This question already has answers here:
FindBugs warning: Inefficient use of keySet iterator instead of entrySet iterator
(5 answers)
Closed 1 year ago.
Existing Code:
Map<?, ?> rolePrincipleMap = cnRoleHolder.getRolePrincipalMap();
Iterator<?> cnRoleIterator = rolePrincipleMap.keySet().iterator();
while (cnRoleIterator.hasNext()) {
Object cnRole = cnRoleIterator.next();
if (!SUBMITTER.equals(cnRole.toString())) {
ArrayList<?> cnRoleMembersList = (ArrayList<?>) rolePrincipleMap.get(cnRole);
//operations
}}
Error is in line where ArraList is defined. Pls help to update the code.
That error warns you that you are accessing the map to retrieve all the keys, and then for some keys, you access the map again to retrieve the value. It is more efficient to retrieve the entries of the map, as each entry has the key and value already:
for ( Map.Entry<?, ?> entry : rolePrincipleMap.entrySet() ) {
Object cnRole = entry.getKey();
if (!SUBMITTER.equals(cnRole.toString())) {
ArrayList<?> cnRoleMembersList = (ArrayList<?>) entry.getValue();
//operations
}
}
I want to iterate a HashMap like:
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
map.replace(entry.getKey(), entry.getValue()-1);
if (entry.getValue() == 0) {
map.remove(entry.getKey(), 0);
}
}
This ends in an Exception: java.util.ConcurrentModificationException
Any solutions?
Kind regards
Iterator<Map.Entry<Integer, Integer>> entryItr = map.entrySet().iterator();
while (entryItr.hasNext()) {
Map.Entry<Integer, Integer> entry = entryItr.next();
if (entry.getValue() > 1) {
entry.setValue(entry.getValue() - 1);
} else {
entryItr.remove();
}
}
You're removing items from the map as you're iterating through it. This is what's causing the exception.
To get a bit of intuition as to why this is: if your map contains three items and on the first iteration you remove the first item, should the next item be the second, or third? i.e. should the iteration continue as though the removed item was still there? And if so, how?
You can get around this by using an iterator on the map which safely goes through each element of the map.
You can't remove elements from an existing Set without using Iterator, otherwise, it will throw ConcurrentModificationException
So, place values to a new Map object if(value-1 !=0) as shown below:
Map<Integer, Integer> map = new HashMap<>();
Map<Integer, Integer> newMap = new HashMap<>();
Iterator<Integer> iterator =map.keySet().iterator();
while(iterator.hasNext()) {
int key = iterator.next();
int value = map.get(key);
if(value-1 !=0) {
newMap.put(key, value-1);
}
}
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.
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?
}
I'm new to hash table and I'm just figuring out the basic operations on it.
I have a hash table created as shown below and inserted values also.
Hashtable<Integer , String> ht = new Hashtable<Integer , String>();
ht.put(1234, "ABCD");
ht.put(2345, "EFGH");
ht.put(4567, "IJKL");
I am able to delete the element needed using the key as shown below
System.out.println("Deleting entry with key 2345");
ht.remove(2345);
System.out.println(ht.toString());
which gives the following output
Deleting entry with key 2345
{4567=IJKL, 1234=ABCD}
I am not able to find any method which helps with locating the element in the hashtable using the value as an index and deleting the element. How do I go about it?
try this
ht.values().remove("ABCD");
this will remove one entry with the specified value, if there may be multiple entries with the same value you can use this
ht.values().removeAll(Collections.singleton("ABCD"));
Navigate using Map.entrySet() and check for Map.Entry#getValue() equality.
You can have a value multiple times so iterate entrySet using an Iterator and delete elements using Iterator.remove()
void deleteItem(String item) {
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
if(entry.getValue().equals(item)) {
it.remove();
}
}
}
Map<Integer, String> map = ...
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
// Remove entry if value equals xxx.
if (entry.getValue() != null && entry.getValue().equals("X")) {
// Do something
}
}