java - 重置 HashMap 中的所有值而不迭代?

标签 java hashmap

如果条件失败,我正在尝试将 HashMap 中的所有值重置为某个默认值。

目前,我正在通过迭代所有键并单独重置值来实现此目的。
是否有任何可能的方法可以在不迭代的情况下为所有键设置相同的值?

类似于:

hm.putAll("some val")  //hm is hashmap object

最佳答案

你无法避免迭代,但如果你使用 ,您可以使用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/

相关文章:

java - 是否有必要在 pom 中指定 maven 插件的版本?

Java 通用类型语法

Java 编写/编辑属性文件

Java:使用类作为 hashmap 中的值

java - HashMap值的计算

java - 通过返回 ArrayList 并为其赋值,将 Element 添加到 HashMap 中的 ArrayList

java - ResultActions 类型中的方法 andExpect(ResultMatcher) 不适用于参数 (RequestMatcher)

java - 如何让两个线程同时工作

java - 使用对象列表作为字段覆盖类的哈希码方法

java - 在 Java 中复制 map 对象