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.
Related
This question already has answers here:
is the Java HashMap keySet() iteration order consistent?
(12 answers)
Closed 2 years ago.
I have a question about the sequence of hash map. For example, in the following code:
public class MapEntrySetOrder {
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
String[] l = new String[]{"Entry", "Set", "HashMap", "Order"};
for (String s : l) {
map.putIfAbsent(s, s);
}
for(Map.Entry<String, String> e : map.entrySet()) {
System.out.println("key:" + e.getKey());
}
}
}
I know there is no order maintained in hashmap, but every time I print the keys thru a loop, there are all in same order, and the order is not from the beginning of the original list nor from the end of the original list:
key:Order
key:Entry
key:Set
key:HashMap
So how is the order decided. If it is in a random way, why every time I print they are the same result?
Use HashMap for fast non-ordered Map
Use LinkedHashMap for order of adding to the Map
Use TreeMap for any order you wish (with Comparator implementation)
Also I think you have same order each time because you use map.entrySet() instead of map.keySet()
Hashmap does not guarantee any order.
If you want ordered sequence use LinkedHashMap instead.
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);
}
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?
}
This question already has answers here:
Java Class that implements Map and keeps insertion order?
(8 answers)
Closed 9 years ago.
So i've created an hashmap, but i need to get the first key that i entered.
This is the code i'm using:
First:
public static Map<String, Inventory> banks = new HashMap<String, Inventory>();
Second:
for(int i = 0; i < banks.size(); i++) {
InventoryManager.saveToYaml(banks.get(i), size, //GET HERE);
}
Where it says //GET HERE i want to get the String from the hasmap.
Thanks for help.
HashMap does not manatain the order of insertion of keys.
LinkedHashMap should be used as it provides predictable iteration order which is normally the order in which keys were inserted into the map (insertion-order).
You can use the MapEntry method to iterate over your the LinkedHashMap. So here is what you need to do in your code. First change your banks map from HashMap to the LinkedHashMap:
public static Map<String, Inventory> banks = new LinkedHashMap<String, Inventory>();
And then simply iterate it like this:
for (Map.Entry<String, Inventory> entry : banks.entrySet()) {
InventoryManager.saveToYaml(entry.getValue(), size, entry.getKey());
}
If you just need the first element of the LinkedHashMap then you can do this:
banks.entrySet().iterator().next();
Answering the question in the title: to get the first key that was inserted, do this:
public static Map<String, Inventory> banks
= new LinkedHashMap<String, Inventory>();
String firstKey = banks.keySet().iterator().next();
Notice that you must use a LinkedHashMap to preserve the same insertion order when iterating over a map. To iterate over each of the keys in order, starting with the first, do this (and I believe this is what you intended):
for (Map.Entry<String, Inventory> entry : banks.entrySet()) {
InventoryManager.saveToYaml(entry.getValue(), size, entry.getKey());
}
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().