我有一个HashMap
和一些Keys - Values
。
在某些情况下,我想将所有值更新为单个值,而不考虑键。
是否有任何util或预定义的方法来做到这一点,没有for循环?
有什么建议吗?
if (yourCondition) {
for (Map.Entry<String, String> entry : map.entrySet()) {
map.put(entry.getKey(), MY_VALUE);
}
}
对于java 8或更高版本(不带循环)
if (yourCondition) {
map.replaceAll( (k,v)->v=MY_VALUE );
}
可以对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...
}
请注意,迭代器的内部实现仍然使用for循环:)
尝试使用番石榴:
Collections2.transform(stringStringHashMap.values(), new Function<String, String>() {
@Override
public String apply(java.lang.String s) {
return "modified string";
}
});
扩展HashMap并使您的实现在设置某些条件时返回您的魔术值。
您计划如何将其设置为单个值尚不清楚,但您可以在HashMap
上调用putAll
,如以下答案所示:
Map tmp = new HashMap(patch);
tmp.keySet().removeAll(target.keySet());
target.putAll(tmp);
patch
是添加到target
的map
。
patch
可以是包含所有键相同值的HashMap
....