如果条件失败,我正在尝试将 HashMap
中的所有值重置为某个默认值。
目前,我正在通过迭代所有键并单独重置值来实现此目的。
是否有任何可能的方法可以在不迭代的情况下为所有键设置相同的值?
类似于:
hm.putAll("some val") //hm is hashmap object
最佳答案
你无法避免迭代,但如果你使用java-8 ,您可以使用replaceAll
方法将为您做到这一点。
Apply the specified function to each entry in this map, replacing each entry's value with the result of calling the function's Function#map method with the current entry's key and value.
m.replaceAll((k,v) -> yourDefaultValue);
基本上,它会迭代映射所保存的表的每个节点,并影响每个值的函数的返回值。
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
Node<K,V>[] tab;
if (function == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
e.value = function.apply(e.key, e.value); //<-- here
}
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
示例:
public static void main (String[] args){
Map<String, Integer> m = new HashMap<>();
m.put("1",1);
m.put("2",2);
System.out.println(m);
m.replaceAll((k,v) -> null);
System.out.println(m);
}
输出:
{1=1, 2=2}
{1=null, 2=null}
关于java - 重置 HashMap 中的所有值而不迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22764871/