I have a HashMap
with some Keys - Values
.
On some condition I want to update all values to single value regardless of keys.
Is there any util or predefined methods to do this, without for loop?
Any suggestions?
I have a HashMap
with some Keys - Values
.
On some condition I want to update all values to single value regardless of keys.
Is there any util or predefined methods to do this, without for loop?
Any suggestions?
if (yourCondition) {
for (Map.Entry<String, String> entry : map.entrySet()) {
map.put(entry.getKey(), MY_VALUE);
}
}
Or for java 8 or higher (without a loop)
if (yourCondition) {
map.replaceAll( (k,v)->v=MY_VALUE );
}
You can use iterator on entrySet:
Iterator it = yourMap.entrySet().iterator();
Map.Entry keyValue;
while (it.hasNext()) {
keyValue = (Map.Entry)it.next();
//Now you can have the keys and values and easily replace the values...
}
Note that the internal implementation of the iterator still uses a for loop :)
Try to use Guava:
Collections2.transform(stringStringHashMap.values(), new Function<String, String>() {
@Override
public String apply(java.lang.String s) {
return "modified string";
}
});
Extend the HashMap and make your implementation return your magic value if some condition is set.
It's not clear how you plan to set it to a single value, but you can call putAll
on the HashMap
as demonstrated from this answer:
Map tmp = new HashMap(patch);
tmp.keySet().removeAll(target.keySet());
target.putAll(tmp);
patch
is the map
you are adding to target
.
patch
could be a HashMap
containing the same value for all keys....