-1

I have a map like this.

HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("sun",0);
map.put("Sunday",0);
map.put("sund",0);
map.put("Mon", 1);
map.put("Tues", 2);
map.put("Wed", 3);

I want to change the entries having the value 0 to new value 7.ie, something like this:

map.put("sun",7);
map.put("Sunday",7);
map.put("sund",7);

How can i do this ?? Thanks

Dinoop Nair
  • 2,663
  • 6
  • 31
  • 51

6 Answers6

2

try this

    for(Entry<String, Integer> e : map.entrySet()) {
        if (e.getValue() == 0) {
            e.setValue(0);
        }
    }
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

use this code ,may help you:

if (hashMap1.containsKey(key))
{
   valuesCopy = hashMap1.get(key); // first, copy out the existing values
   valuesCopy.add(newValues++); // insert the newValues to the value Set
   hashMap1.put(key, valuesCopy); // insert the key-value pairs
}
prakash
  • 1,413
  • 1
  • 21
  • 33
1

you can do this by:

 for(Map.Entry<String, Integer> e: map.entrySet()){
        if(0 == (e.getValue())) {
            e.setValue(7);
        }
    }
Shekhar Khairnar
  • 2,643
  • 3
  • 26
  • 44
1
for(Entry<String,Integer> entry : map.entrySet()) {
     if(e.getValue() == 0) {
         e.setValue(7);
     }
}

It should Work.

jaggs
  • 298
  • 2
  • 9
  • 28
0
Set<String> keyValues = map.keySet();

for(String s : keyValues){
   int i = map.get(s);
   if(i == 0)
    {
      map.put(s,7);
     }
}
Siva
  • 1,938
  • 1
  • 17
  • 36
-1

Try this Courtesy : http://www.fluffycat.com/Java/HashMaps/

HashMap methods to alter what is in the HashMap

Object objectReplacedForKey = 
  hashMapName.put(objectKey, objectToAdd); 

hashMapName.putAll(mapToAdd); 
hashMapName.remove(keyObject);  
hashMapName.clear();
Alok
  • 2,629
  • 4
  • 28
  • 40