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

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().

Related

SpotBugs warning: Inefficient use of keySet iterator instead of entrySet iterator [duplicate]

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
}
}

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 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's Iterator to prevent concurrent modification [duplicate]

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?
}

How do I get out the corresponding key of the value in that HashMap? [duplicate]

This question already has answers here:
Java Hashmap: How to get key from value?
(39 answers)
Closed 8 years ago.
How do I print out the corresponding key of the value in that map? I don't think there's a getKey() method for a HashMap.
Map <Integer, String > map1 = new HashMap <Integer, String> ();
map1.put(7,"GREAT");
map1.put(8,"Try Again!");
if (map1.containsValue("GREAT")){
System.out.println(WHAT DO I PUT HERE?);
}
Try This:
Map <Integer, String > map1 = new HashMap <Integer, String> ();
map1.put(7,"GREAT");
map1.put(8,"Try Again!");
Integer key=null;
Set<Integer>keySet=new HashSet<Integer>();
if (map1.containsValue("GREAT")){
keySet=map1.keySet();
Iterator<Integer>iter=keySet.iterator();
while(iter.hasNext()){
if(map1.get(key=iter.next()).equals("GREAT")){
break;
}
}
}
System.out.println("Key is:"+key);
}

Categories

Resources