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);
Related
Below are the scenario of iterator and for loop:
1) Using iterator:
ihm.put("Zara", new Double(3434.34));
ihm.put("Mahnaz", new Double(123.22));
ihm.put("Ayan", new Double(1378.00));
ihm.put("Daisy", new Double(99.22));
ihm.put("Qadir", new Double(-19.08));
// Get a set of the entries
Set set = ihm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
=====================================
Using For Loop:
HashMap<String, Integer> map = new HashMap<String, Integer>();
//Adding key-value pairs
map.put("ONE", 1);
map.put("TWO", 2);
map.put("THREE", 3);
map.put("FOUR", 4);
//Adds key-value pair 'ONE-111' only if it is not present in map
map.putIfAbsent("ONE", 111);
//Adds key-value pair 'FIVE-5' only if it is not present in map
map.putIfAbsent("FIVE", 5);
//Printing key-value pairs of map
Set<Entry<String, Integer>> entrySet = map.entrySet();
for (Entry<String, Integer> entry : entrySet)
{
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
In the above both cases iterator and for loop are doing the same job.So can anyone tell me what is the differences between them and when i can use iterator and for loop.
The only significant difference between loop and iterator (apart from readability) is that while using iterator you can edit content of the collection through that Iterator instance.
If you try to edit map while looping through it you will get Concurrent ModificationException
You should use iterator when you want to update map while iterating over it e.g. remove entries which match some conditions.
Iterator<Entry> it = map.iterator();
while(it.hasNext())
if(check(it.next()))
it.remove();
I have to note that for-loop is a syntactic sugar for iterator and in resulting bytecode they will look the same way.
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 am adding few item on finalMapNode using map for creating json for d3. and i dont want any duplicates item. how to check.finalmapNode put the duplicates item on map.I dont want duplicated item.if item is avalible then it should not put on map . if id is avalable then item should not put in the finalmapnode.
Note::if id is avalable then item should not put in the finalmapnode.
List<Map<String, Object>> listNodeMap = new ArrayList<Map<String, Object>>();
Map<String, Object> finalMapNode2 = new TreeMap<String, Object>();
Map<String, Object> finalMapNode = new TreeMap<String, Object>();
//if id is avalable then item should not put in the finalmapnode.
finalMapNode.put("id", Integer.parseInt(source2.get(z))+"");
finalMapNode.put("name",source.get(z));
finalMapNode.put("displayname", source.get(z));
finalMapNode.put("image", "/xxxxx/resources/icon/location.png");
finalMapNode.put("type", "location");
finalMapNode.put("group", 0);
finalMapNode.put("opacity", 100);
finalMapNode2.put("id", Integer.parseInt(target2.get(z))+"");
finalMapNode2.put("name",target.get(z));
finalMapNode2.put("displayname", target.get(z));
finalMapNode2.put("image", "/xxxxx/resources/icon/location.png");
finalMapNode2.put("type", "location");
finalMapNode2.put("group", 0);
finalMapNode2.put("opacity", 100);
listNodeMap.add(finalMapNode);
listNodeMap.add(finalMapNode2);
When you try to add the KEY which is already available in the hashmap, then it will override the previous KEY's VALUE and adds the new VALUE. So its up to you to validate the map before trying to add the KEY and VALUE. You can use finalmapnode.containsKey(KEY); to validate and then add the VALUES.
EDIT
Just check the below method works for you!
private static void putMap(String strKey, Object object, Map<String, Object> map){
if(!map.containsKey(strKey)){
map.put(strKey, object);
}
}
In your case, instead of using
finalMapNode.put("name",source.get(z));
you can use
putMap("name",source.get(z), finalMapNode);
The above method will not override the values if you add duplicate KEYS. Pass the KEY, VALUE and the Map which you declared as finalMapNode.
Try this and see.
Thanks!
HashMap<String, String> map = new HashMap<String, String>();
map.put("A", "1");
map.put("B", "2");
map.put("C", "2");
map.put("D", "3");
map.put("E", "3");
HashMap<String, String> mapNew = new HashMap<String, String>();
for(String s :map.keySet())
{
//String value = map.get(s);
System.out.println(s +"=="+map.get(s));
if(!mapNew.containsValue(map.get(s)))
{
mapNew.put(s, map.get(s));
}
}
System.out.println(mapNew);
before :{A=1,B=2,c=2,D=3,E=3}
Output after removing duplicates : {A=1,B=2,D=3}
This question already has answers here:
How can I combine two HashMap objects containing the same types?
(17 answers)
Closed 9 years ago.
I have two HashMaps defined like so:
HashMap<String, List<Incident>> map1 = new HashMap<String, List<Incident>>();
HashMap<String, List<Incident>> map2 = new HashMap<String, List<Incident>>();
Also, I have a 3rd HashMap Object:
HashMap<String, List<Incident>> map3;
and the merge list when combine both.
In short, you can't. map3 doesn't have the correct types to merge map1 and map2 into it.
However if it was also a HashMap<String, List<Incident>>. You could use the putAll method.
map3 = new HashMap<String, List<Incident>>();
map3.putAll(map1);
map3.putAll(map2);
If you wanted to merge the lists inside the HashMap. You could instead do this.
map3 = new HashMap<String, List<Incident>>();
map3.putAll(map1);
for(String key : map2.keySet()) {
List<Incident> list2 = map2.get(key);
List<Incident> list3 = map3.get(key);
if(list3 != null) {
list3.addAll(list2);
} else {
map3.put(key,list2);
}
}
create third map and use putAll() method to add data from ma
HashMap<String, Integer> map1 = new HashMap<String, Integer>();
HashMap<String, Integer> map2 = new HashMap<String, Integer>();
HashMap<String, Integer> map3 = new HashMap<String, Integer>();
map3.putAll(map1);
map3.putAll(map2);
You have different type in question for map3 if that is not by mistake then you need to iterate through both map using EntrySet
Use commons collections:
Map<String, List<Incident>> combined = CollectionUtils.union(map1, map2);
If you want an Integer map, I suppose you could apply the .hashCode method to all values in your Map.
HashMap has a putAll method.
Refer this :
http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
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.